Starter project
Supabase pg_cron NHL data ingestion starter
Summary
This starter uses pg_cron to call a Supabase Edge Function every morning. The function pulls yesterday's and today's NHL games from PuckAPI and upserts them into a Postgres table keyed on game id. Re-runs are safe. You copy two SQL files and two TypeScript files, set one secret, and the table fills itself.
What you'll build
A table called nhl_games that holds one row per NHL game: teams, start time, score, game state, venue and how the game ended. A scheduled job refreshes it once a day. Scores for games that finish after the previous run are corrected by the next run, because every run re-reads a two-day window and overwrites the score and state columns.
The design splits the work into three small pieces on purpose. SQL owns the data shape and the upsert, so the same function works from a cron job, a manual call or a test. The Edge Function owns the network call and the API key. pg_cron owns the clock. Each piece can be swapped without touching the others, which matters later when you add odds, standings or play-by-play tables beside this one.
Prerequisites
- A Supabase project that is yours to experiment in, with the pg_cron, pg_net and Vault extensions enabled. All three are available on the free tier.
- The Supabase CLI, signed in and linked to the project.
- A PuckAPI key. Store it as an Edge Function secret, never in the repo and never in a SQL file.
- Deno 2 if you want to run the local check. The deployed function runs on the Supabase Edge runtime and needs nothing installed.
Basic comfort with SQL and TypeScript is enough. You do not need to know the NHL schedule format, because the API returns flat JSON with one object per game.
The project
The tree is small enough to type out by hand:
nhl-ingest/
supabase/
migrations/
20261206000000_nhl_games.sql table, index, row level security, upsert function
20261206000100_schedule.sql pg_cron job that calls the Edge Function
functions/
ingest-nhl-games/
ingest.ts fetch + call the upsert (pure logic, testable)
index.ts Deno.serve wrapper using the service role client
verify.ts optional local check against an in-process PostgresThe first migration creates the table and one function. ingest_nhl_games(payload jsonb) takes the raw API response and walks data.games with jsonb_array_elements. Taking the whole response, not a pre-cooked array, means the Edge Function stays a thin pipe and you can replay a saved response through the same function. Row level security is switched on with no public policy, and only the service role can execute the function, so browser clients cannot write to the table or call it.
`supabase/migrations/20261206000000_nhl_games.sql`
-- Table, upsert function. Runs on any Postgres 14+.
create table if not exists public.nhl_games (
game_id text primary key,
season text not null,
game_date date not null,
start_time timestamptz,
home_team text not null,
away_team text not null,
home_score integer,
away_score integer,
game_state text,
game_type text,
venue text,
ended_in text,
fetched_at timestamptz not null default now()
);
create index if not exists nhl_games_date_idx on public.nhl_games (game_date);
alter table public.nhl_games enable row level security;
-- Takes the raw API response ({"data": {"games": [...]}}) and upserts it.
-- Returns the number of rows written.
create or replace function public.ingest_nhl_games(payload jsonb)
returns integer
language plpgsql
security definer
set search_path = public
as $$
declare
written integer;
begin
with incoming as (
select
g->>'id' as game_id,
g->>'season' as season,
(g->>'gameDate')::date as game_date,
(g->>'startTime')::timestamptz as start_time,
g->>'homeTeam' as home_team,
g->>'awayTeam' as away_team,
nullif(g->>'homeScore', '')::integer as home_score,
nullif(g->>'awayScore', '')::integer as away_score,
g->>'gameState' as game_state,
g->>'gameType' as game_type,
g->>'venue' as venue,
g->>'endedIn' as ended_in
from jsonb_array_elements(coalesce(payload #> '{data,games}', '[]'::jsonb)) as g
), up as (
insert into public.nhl_games as t
(game_id, season, game_date, start_time, home_team, away_team,
home_score, away_score, game_state, game_type, venue, ended_in)
select game_id, season, game_date, start_time, home_team, away_team,
home_score, away_score, game_state, game_type, venue, ended_in
from incoming
on conflict (game_id) do update set
home_score = excluded.home_score,
away_score = excluded.away_score,
game_state = excluded.game_state,
start_time = excluded.start_time,
ended_in = excluded.ended_in,
fetched_at = now()
returning 1
)
select count(*) into written from up;
return written;
end;
$$;
revoke all on function public.ingest_nhl_games(jsonb) from public, anon, authenticated;
grant execute on function public.ingest_nhl_games(jsonb) to service_role;
grant all on table public.nhl_games to service_role;The second migration schedules the job. Cron expressions in pg_cron use UTC. Eleven thirty UTC is early morning in North America, after every game from the previous night has finished. The job posts to the function URL with the service role key, both read from Vault so neither appears in cron.job.
`supabase/migrations/20261206000100_schedule.sql`
-- Needs the pg_cron, pg_net and vault extensions (enable them in the dashboard).
create extension if not exists pg_cron;
create extension if not exists pg_net;
-- One-time: store the project URL and service role key in Vault.
-- select vault.create_secret('https://YOUR-REF.supabase.co', 'project_url');
-- select vault.create_secret('YOUR-SERVICE-ROLE-KEY', 'service_role_key');
select cron.schedule(
'ingest-nhl-games-daily',
'30 11 * * *', -- 11:30 UTC, after the previous night's games are final
$$
select net.http_post(
url := (select decrypted_secret from vault.decrypted_secrets where name = 'project_url')
|| '/functions/v1/ingest-nhl-games',
headers := jsonb_build_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' ||
(select decrypted_secret from vault.decrypted_secrets where name = 'service_role_key')
),
body := '{}'::jsonb,
timeout_milliseconds := 30000
);
$$
);ingest.ts holds the logic. It computes a two-day window, calls get_games with date_from, date_to and a limit of 500, and passes the parsed response to the database. The base URL defaults to the PuckAPI host and can be overridden with API_BASE_URL. The rpc argument is injected, so the same code runs against the real Supabase client in production and against a local database in tests.
`supabase/functions/ingest-nhl-games/ingest.ts`
const BASE = Deno.env.get("API_BASE_URL") ?? "https://mcp.puckapi.com/v1";
export function isoDay(d: Date): string {
return d.toISOString().slice(0, 10);
}
export async function fetchGames(apiKey: string, from: string, to: string) {
const res = await fetch(`${BASE}/get_games`, {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": apiKey },
body: JSON.stringify({ date_from: from, date_to: to, limit: 500 }),
});
if (!res.ok) {
throw new Error(`get_games failed: ${res.status} ${await res.text()}`);
}
return await res.json(); // { data: { games: [...], count } }
}
// `rpc` is supabase.rpc.bind(supabase) in production, a stub in tests.
export async function run(
apiKey: string,
rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<{ data: unknown; error: { message: string } | null }>,
now = new Date(),
) {
const to = isoDay(now);
const from = isoDay(new Date(now.getTime() - 24 * 3600 * 1000));
const payload = await fetchGames(apiKey, from, to);
const { data, error } = await rpc("ingest_nhl_games", { payload });
if (error) throw new Error(error.message);
return { from, to, fetched: payload.data.games.length, written: data };
}index.ts is the thin entry point. It builds a service role client from environment variables that Supabase provides, reads the API key from your secret, and returns the result as JSON. Errors come back as HTTP 500 so pg_net logs them.
`supabase/functions/ingest-nhl-games/index.ts`
import { createClient } from "npm:@supabase/supabase-js@2";
import { run } from "./ingest.ts";
Deno.serve(async () => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
try {
const result = await run(
Deno.env.get("PUCKAPI_KEY")!,
(fn, args) => supabase.rpc(fn, args),
);
return Response.json(result);
} catch (e) {
return Response.json({ error: String(e) }, { status: 500 });
}
});The last file is optional. It loads the migration into PGlite, an in-process Postgres, runs the real fetch twice and prints the row count, which proves the upsert is idempotent without touching your project.
`verify.ts`
// Local check: real API fetch -> real Postgres engine (PGlite) running the migration.
import { PGlite } from "npm:@electric-sql/pglite@0.2.17";
import { run } from "./supabase/functions/ingest-nhl-games/ingest.ts";
const db = new PGlite();
// Supabase ships these roles; a bare Postgres does not.
await db.exec("create role anon; create role authenticated; create role service_role;");
await db.exec(await Deno.readTextFile("supabase/migrations/20261206000000_nhl_games.sql")
.catch(() => ""));
const rpc = async (_fn: string, args: Record<string, unknown>) => {
try {
const r = await db.query("select public.ingest_nhl_games($1::jsonb) as n", [JSON.stringify(args.payload)]);
return { data: (r.rows[0] as { n: number }).n, error: null };
} catch (e) { return { data: null, error: { message: String(e) } }; }
};
const key = Deno.env.get("PUCKAPI_KEY")!;
const day = new Date("2026-12-06T12:00:00Z");
const first = await run(key, rpc, day);
const second = await run(key, rpc, day);
const c = await db.query("select count(*)::int n, count(*) filter (where game_state in ('OFF','FINAL'))::int fin, min(game_date)::text lo, max(game_date)::text hi from public.nhl_games");
console.log(JSON.stringify({ first, second, table: c.rows[0] }));
const s = await db.query("select game_id, game_date::text, home_team, away_team, home_score, away_score, game_state from public.nhl_games order by game_date, game_id limit 3");
console.log(JSON.stringify(s.rows));How to run it
- Create the files above inside a folder where you have run
supabase init. - Store the API key as a secret with
supabase secrets set PUCKAPI_KEY=your-key. - Push the schema with
supabase db push. The second migration needs the extensions, so enable pg_cron, pg_net and Vault in the dashboard first. - Deploy the function with
supabase functions deploy ingest-nhl-games. - In the SQL editor, run the two
vault.create_secretlines from the schedule migration with your project URL and service role key. - Trigger one run by hand by calling the function URL once with
curland the service role key, then runselect count(*) from public.nhl_games;. - Confirm the schedule with
select jobname, schedule from cron.job;and look atcron.job_run_detailsthe next morning.
To check the logic without a project, run PUCKAPI_KEY=your-key deno run -A verify.ts. You should see the games for the two-day window, 18 when this page was checked, and the same count on the second run.
How to extend it
- More tables from the same pattern. Add
get_standingsorget_team_statswith their own upsert functions and one morecron.scheduleline each. Keep one Edge Function per table so a failing endpoint cannot block the others. - A backfill job. Call
get_gameswith aseasonand page through it usinglimitandoffset. Run it once by hand with a larger timeout, then let the daily job maintain the tail. - Change-only writes. Add a
whereclause to thedo updateso unchanged rows are not rewritten, and keep a smallingest_logtable with the window, fetched count and written count for each run. - A read API for your app. Add a
selectpolicy for theauthenticatedrole on a view that hides internal columns, then query it from the browser with the anon key.
Limits and when not to use this
This pattern is for a daily or hourly refresh of small tables. It is not a live scoreboard. An Edge Function has an execution time limit that is short on the free tier, so a long backfill belongs in a script you run yourself.
The Edge Function holds your API key and your credits. Anyone who can invoke it with a valid bearer token can spend credits, so keep JWT verification on, which is the default, and do not expose the function URL in client code.
The data is yours to store and query for your own product. The terms do not let you republish it as a raw feed or dataset. If your app serves it to users, serve derived views, not a pass-through.
Skip this stack if you already run a worker queue or a workflow tool, or if you need sub-minute freshness. In those cases call the API from the process that already exists.
Finally, the response envelope matters. The live API wraps results in a top-level data object, and this code reads data.games. If you copy snippets from other sources that show a bare games array, adjust the path in ingest_nhl_games.
FAQ
Can I call the API straight from SQL with pg_net instead of an Edge Function? Yes, pg_net can post to the API, but it is asynchronous and stores the response in a separate table, so you need a second job to parse it. An Edge Function keeps the key out of SQL, handles errors in one place, and hands the raw response to a single upsert function.
How many credits does a daily run cost? One get_games call is 5 credits on PuckAPI, so a daily run is 5 credits, about 150 a month. Check the credit table in the PuckAPI docs before you widen the date range or add odds calls, which cost more.
What happens if the API is down when the job fires? The Edge Function returns a 500, pg_net records the failure, and the next day's run covers yesterday and today again. Because rows upsert on game id, a missed run leaves a gap of at most one day, and a manual invoke fills it.
Live from the API
Free to embed on your own site, with no key needed. Get the embed code.
Get a free key Or download whole seasons as Parquet
Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.