25 lines · 1.4 KBRaw
| 1 | import { recordRunFinished } from "./sessions.ts"; |
| 2 | |
| 3 | /** The refs CLI's API. Every request carries an OAuth access token, checked before this handler runs. */ |
| 4 | export const cliApi = { |
| 5 | async fetch(request, env, ctx) { |
| 6 | const userId = (ctx as ExecutionContext & { props?: { userId?: string } }).props?.userId; |
| 7 | if (!userId) return new Response("Unauthorized\n", { status: 401 }); |
| 8 | const { pathname } = new URL(request.url); |
| 9 | |
| 10 | if (pathname === "/api/cli/connect") { |
| 11 | const headers = new Headers(request.headers); |
| 12 | headers.set("x-refs-user", userId); |
| 13 | return env.USER_HUB.get(env.USER_HUB.idFromName(userId)).fetch(new Request(request, { headers })); |
| 14 | } |
| 15 | if (pathname === "/api/cli/whoami") { |
| 16 | const person = await env.DB.prepare("SELECT id, name, email FROM users WHERE id = ?").bind(userId).first<{ id: string; name: string; email: string }>(); |
| 17 | return person ? Response.json(person) : new Response("Not found\n", { status: 404 }); |
| 18 | } |
| 19 | if (pathname === "/api/cli/runs/finished" && request.method === "POST") { |
| 20 | const recorded = await recordRunFinished(env, userId, (await request.json().catch(() => ({}))) as Record<string, unknown>); |
| 21 | return recorded ? new Response(null, { status: 204 }) : new Response("No such run\n", { status: 404 }); |
| 22 | } |
| 23 | return new Response("Not found\n", { status: 404 }); |
| 24 | }, |
| 25 | } satisfies ExportedHandler<Env>; |