|
| 1 | +import { |
| 2 | + type CustomMutatorImpl as CustomMutatorFn, |
| 3 | + type Schema, |
| 4 | + withValidation, |
| 5 | +} from "@rocicorp/zero" |
| 6 | +import { |
| 7 | + PostgresJSConnection, |
| 8 | + PushProcessor, |
| 9 | + type ServerTransaction, |
| 10 | + ZQLDatabase, |
| 11 | +} from "@rocicorp/zero/pg" |
| 12 | +import { handleGetQueriesRequest } from "@rocicorp/zero/server" |
| 13 | +import postgres from "postgres" |
| 14 | +import * as z from "zod/mini" |
| 15 | +import { AuthData } from "../shared/auth.ts" |
| 16 | +import { jsonCodec } from "../shared/codec.ts" |
| 17 | +import { createMutators, type mutators } from "../shared/mutators.ts" |
| 18 | +import * as queries from "../shared/queries.ts" |
| 19 | +import { schema } from "../shared/schema.ts" |
| 20 | +import * as Cookie from "./lib/cookie.ts" |
| 21 | +import * as Urls from "./lib/urls.ts" |
| 22 | + |
| 23 | +export default { |
| 24 | + async fetch(req, env) { |
| 25 | + const url = new URL(req.url) |
| 26 | + const headers = { |
| 27 | + "Access-Control-Allow-Credentials": "true", |
| 28 | + "Access-Control-Allow-Headers": "Content-Type, Authorization", |
| 29 | + "Access-Control-Allow-Methods": "POST, OPTIONS", |
| 30 | + "Access-Control-Allow-Origin": Urls.origins( |
| 31 | + Urls.fromString(env.APP_URL), |
| 32 | + ).join(","), |
| 33 | + "Access-Control-Max-Age": "86400", |
| 34 | + } satisfies HeadersInit |
| 35 | + |
| 36 | + if (req.method === "OPTIONS") |
| 37 | + return new Response(null, { headers, status: 204 }) |
| 38 | + |
| 39 | + if (req.method === "GET" && url.pathname === "/ping") |
| 40 | + return new Response("pong", { headers, status: 200 }) |
| 41 | + |
| 42 | + if ( |
| 43 | + req.method !== "POST" && |
| 44 | + !(url.pathname === "/mutate" || url.pathname === "/queries") |
| 45 | + ) |
| 46 | + return new Response("Not found", { headers, status: 404 }) |
| 47 | + |
| 48 | + try { |
| 49 | + const cookieRaw = |
| 50 | + req.headers.get("Cookie") ?? |
| 51 | + // Using `Authorization` header for test compat |
| 52 | + req.headers |
| 53 | + .get("authorization") |
| 54 | + ?.replace("Bearer ", "") ?? |
| 55 | + null |
| 56 | + const cookie = await Cookie.parseSigned( |
| 57 | + cookieRaw, |
| 58 | + env.AUTH_SECRET, |
| 59 | + "ztest.auth", |
| 60 | + ) |
| 61 | + const authData = cookie |
| 62 | + ? z.decode(jsonCodec(AuthData), cookie) |
| 63 | + : undefined |
| 64 | + |
| 65 | + if (url.pathname === "/queries") { |
| 66 | + const result = await handleGetQueriesRequest( |
| 67 | + (name, args) => { |
| 68 | + const q = validated[name] |
| 69 | + if (!q) throw new Error(`No such query: ${name}`) |
| 70 | + return { query: q(authData, ...args) } |
| 71 | + }, |
| 72 | + schema, |
| 73 | + req, |
| 74 | + ) |
| 75 | + return Response.json(result, { headers, status: 200 }) |
| 76 | + } |
| 77 | + |
| 78 | + const client = createMutators(authData) |
| 79 | + const mutators = { |
| 80 | + ...client, |
| 81 | + } satisfies ServerMutatorDefs |
| 82 | + |
| 83 | + const processor = new PushProcessor( |
| 84 | + new ZQLDatabase( |
| 85 | + new PostgresJSConnection(postgres(env.DB.connectionString)), |
| 86 | + schema, |
| 87 | + ), |
| 88 | + ) |
| 89 | + const result = await processor.process(mutators, req) |
| 90 | + return Response.json(result, { headers, status: 200 }) |
| 91 | + } catch (error) { |
| 92 | + console.error(error) |
| 93 | + return new Response("Internal server error", { headers, status: 500 }) |
| 94 | + } |
| 95 | + }, |
| 96 | +} satisfies ExportedHandler<Pick<Env, "APP_URL" | "AUTH_SECRET" | "DB">> |
| 97 | + |
| 98 | +const validated = Object.fromEntries( |
| 99 | + [ |
| 100 | + queries.me, |
| 101 | + queries.repositoriesForAccount, |
| 102 | + // only used for testing |
| 103 | + queries.getRepository, |
| 104 | + ].map((q) => [q.queryName, withValidation(q)]), |
| 105 | +) |
| 106 | + |
| 107 | +type ServerMutatorDefs = { |
| 108 | + [namespaceOrKey in keyof mutators]: mutators[namespaceOrKey] extends CustomMutatorFn< |
| 109 | + infer schema, |
| 110 | + infer transaction, |
| 111 | + infer args |
| 112 | + > |
| 113 | + ? CustomServerMutatorImpl<schema, transaction, args> |
| 114 | + : { |
| 115 | + [key in keyof mutators[namespaceOrKey]]: mutators[namespaceOrKey][key] extends CustomMutatorFn< |
| 116 | + infer schema, |
| 117 | + infer transaction, |
| 118 | + infer args |
| 119 | + > |
| 120 | + ? CustomServerMutatorImpl<schema, transaction, args> |
| 121 | + : never |
| 122 | + } |
| 123 | +} |
| 124 | +type CustomServerMutatorImpl<schema extends Schema, transaction, args> = ( |
| 125 | + tx: ServerTransaction<schema, transaction>, |
| 126 | + args: args, |
| 127 | +) => Promise<void> |
0 commit comments