export default async()

in netlify/functions/store-ping-data-background/index.ts [93:126]


export default async (req: Request, _context: Context) => {
	// Only allow 'local' requests from our own functions.
	if (!LOCAL_PSK || req.headers.get("Authorization") !== `PSK ${LOCAL_PSK}`) {
		throw new Error("Unauthorized");
	}

	const { date } = await req.json() as { date: string };

	const currentDate = new Date();

	const requestStore = getStore("ping-data-request");
	// Set a marker as a best-effort to prevent multiple concurrent (and
	// unnecessary) background functions for a particular date.
	await requestStore.set(date, currentDate.toISOString());

	const pings: Ping[] = await fetchData(date).catch(e => {
		console.error(e);
		return [];
	});

	const metadata = {
		date: currentDate.toISOString(),
		retry: pings.length === 0 ? currentDate.getTime() + EMPTY_RETRY_MS : 0,
		version: DATA_VERSION
	};

	const condensed = condenseData(pings);
	const gzipped = gzipSync(JSON.stringify(condensed))

	const store = getStore("ping-data");
	await store.set(date, new Blob([gzipped]), { metadata });

	await requestStore.delete(date);
};