Skip to content

gitflarePublicPartly agent-ready40

sketch-rush

Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.

Add the Apache-2.0 licencedbe1e99
TypeScript50 lines2.0 KB
import type { Env } from "./leaderboard.ts";import { topScores } from "./leaderboard.ts";import { isValidCode, randomCode } from "./room-logic.ts"; export { Room } from "./room.ts";export { Lobby } from "./lobby.ts"; const json = (body: unknown, status = 200) =>  new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } }); function lobby(env: Env) {  return env.LOBBY.get(env.LOBBY.idFromName("global")) as unknown as {    stats(): Promise<{ rooms: number; players: number }>;    quickplay(): Promise<string>;  };} export default {  async fetch(request: Request, env: Env): Promise<Response> {    const url = new URL(request.url);    const path = url.pathname;    if (path === "/health") {      try {        const s = await lobby(env).stats();        return json({ ok: true, rooms: s.rooms, players: s.players });      } catch {        return json({ ok: true, rooms: 0, players: 0 });      }    }    if (path === "/api/rooms" && request.method === "POST") {      return json({ code: randomCode(() => crypto.getRandomValues(new Uint32Array(1))[0] / 4294967296) });    }    if (path === "/api/quickplay") return json({ code: await lobby(env).quickplay() });    if (path === "/api/leaderboard") return json(await topScores(env, url.searchParams.get("mode") || "classic"));    if (path.startsWith("/ws/")) {      const code = path.slice(4).toUpperCase();      if (!isValidCode(code)) return new Response("bad room code", { status: 400 });      if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 });      return env.ROOM.get(env.ROOM.idFromName(code)).fetch(withCode(request, code));    }    return env.ASSETS.fetch(request);  },} satisfies ExportedHandler<Env>; function withCode(request: Request, code: string): Request {  const h = new Headers(request.headers);  h.set("x-room-code", code);  return new Request(request, { headers: h });}