feat: use cloudflare kv

This commit is contained in:
uku 2024-10-26 11:50:41 +02:00
parent 8ae9355ec9
commit c2e36adc6a
Signed by: uku
SSH key fingerprint: SHA256:4P0aN6M8ajKukNi6aPOaX0LacanGYtlfjmN+m/sHY/o
8 changed files with 35 additions and 13 deletions

6
src/app.d.ts vendored
View file

@ -6,7 +6,11 @@ declare global {
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
interface Platform {
env?: {
TCL_GUESSR_KV: KVNamespace;
};
}
}
}

View file

@ -35,17 +35,22 @@ let lazyMetro: [GeoJSON.Feature, string][] | null = null;
let lazyTram: [GeoJSON.Feature, string][] | null = null;
let lazyStops: GeoJSON.Feature[] | null = null;
const games: Record<string, GeoJSON.Feature> = {};
export function createGame(stop: GeoJSON.Feature): string {
export async function createGame(stop: GeoJSON.Feature, kv: KVNamespace<string>): Promise<string> {
const uuid = crypto.randomUUID();
games[uuid] = stop;
await kv.put(`game:${uuid}`, JSON.stringify(stop), { expirationTtl: 600 });
return uuid;
}
export function stopGame(uuid: string): GeoJSON.Feature | null {
const stop = games[uuid];
delete games[uuid];
export async function stopGame(
uuid: string,
kv: KVNamespace<string>,
): Promise<GeoJSON.Feature | null> {
const stop: GeoJSON.Feature | null = await kv.get(`game:${uuid}`, "json");
if (stop) await kv.delete(`game:${uuid}`);
return stop;
}

View file

@ -1,9 +1,13 @@
import { stopGame, type CheckData, type CheckResponse } from "$lib";
import { error } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request }) => {
export const POST: RequestHandler = async ({ request, platform }) => {
const kv = platform?.env?.TCL_GUESSR_KV;
if (!kv) return error(500, "could not connect to kv");
const data: CheckData = await request.json();
const stop = stopGame(data.gameId);
const stop = await stopGame(data.gameId, kv);
if (stop) {
// GeoJSON data is LonLat, not LatLon

View file

@ -2,7 +2,10 @@ import type { PageServerLoad } from "./$types";
import { createGame, getMetro, getStops, getTram, type GameData, type GameOptions } from "$lib";
import { error } from "@sveltejs/kit";
export const load: PageServerLoad = async ({ fetch, url }) => {
export const load: PageServerLoad = async ({ fetch, url, platform }) => {
const kv = platform?.env?.TCL_GUESSR_KV;
if (!kv) return error(500, "could not connect to kv");
const stops = await getStops(fetch);
const mode = url.searchParams.get("mode");
@ -40,7 +43,7 @@ export const load: PageServerLoad = async ({ fetch, url }) => {
return error(400, "could not select random stop");
}
const gameId = createGame(randomStop);
const gameId = await createGame(randomStop, kv);
const gameData: GameData = {
lines: options.mode === "easy" || options.mode === "hard" ? lineColors : [],
stops: options.mode === "easy" ? crossingStops : [],