Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

api.ts

141 lines5.1 KB

1import * as Drizzle from "alchemy/Drizzle/Postgres";
2import * as Fly from "alchemy/Fly";
3import { eq, sql } from "drizzle-orm";
4import * as Effect from "effect/Effect";
5import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
6import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
7import { relations, Users } from "./schema.ts";
8import { API_PORT, Db, MIGRATE_TOKEN, Site } from "./shared.ts";
9​
10/**
11 * HTTP Service that binds Managed Postgres via {@link Fly.ConnectPostgres}
12 * and queries through Drizzle.
13 *
14 * Also exposes `POST /migrate`: MPG is only reachable on the org's private
15 * network, so DDL is applied through this in-network Service — the deploy
16 * (or test) posts the generated migration SQL here instead of connecting
17 * to the cluster directly.
18 */
19export default class Api extends Fly.Service<Api>()(
20 "Api",
21 {
22 app: Site,
23 main: import.meta.url,
24 region: "iad",
25 port: API_PORT,
26 guest: { cpuKind: "shared", cpus: 1, memoryMb: 256 },
27 // `pg` is CommonJS — bundling it breaks `Client` under Rolldown's
28 // interop. Install it into the image so `@effect/sql-pg` /
29 // `Drizzle.Postgres` load it with Node's CJS semantics.
30 build: { install: ["pg"] },
31 },
32 Effect.gen(function* () {
33 const conn = yield* Fly.ConnectPostgres(Db);
34 const db = yield* Drizzle.Postgres(conn.connectionString, {
35 relations,
36 });
37 // DDL and other session-scoped statements need the direct
38 // (non-PgBouncer) connection.
39 const directDb = yield* Drizzle.Postgres(conn.directConnectionString);
40​
41 return {
42 fetch: Effect.gen(function* () {
43 const request = yield* HttpServerRequest;
44 const path = new URL(request.url, "http://service").pathname;
45 if (path === "/migrate" && request.method === "POST") {
46 if (request.headers["x-migrate-token"] !== MIGRATE_TOKEN) {
47 return yield* HttpServerResponse.json(
48 { error: "unauthorized" },
49 { status: 401 },
50 );
51 }
52 // drizzle-kit emits one file per migration with statements
53 // separated by `--> statement-breakpoint`. Apply each statement,
54 // tolerating re-runs (the client retries through service warmup,
55 // so a statement may already have been applied).
56 const body = yield* request.text;
57 const statements = body
58 .split("--> statement-breakpoint")
59 .map((statement) => statement.trim())
60 .filter((statement) => statement.length > 0);
61 for (const statement of statements) {
62 yield* directDb.execute(sql.raw(statement)).pipe(
63 Effect.catch((error) =>
64 String(error).includes("already exists")
65 ? Effect.void
66 : Effect.fail(error),
67 ),
68 );
69 }
70 return yield* HttpServerResponse.json({
71 applied: statements.length,
72 });
73 }
74 if (path === "/health") {
75 const users = yield* db.select().from(Users);
76 return yield* HttpServerResponse.json({
77 ok: true,
78 users: users.length,
79 });
80 }
81 switch (request.method) {
82 case "GET": {
83 if (path === "/" || path === "/users") {
84 const users = yield* db.select().from(Users);
85 return yield* HttpServerResponse.json({ users });
86 }
87 const id = Number(path.split("/").pop());
88 if (Number.isNaN(id)) {
89 return yield* HttpServerResponse.json(
90 { error: "Invalid user ID" },
91 { status: 400 },
92 );
93 }
94 const user = yield* db.query.Users.findFirst({
95 where: { id },
96 with: { posts: true },
97 });
98 return yield* HttpServerResponse.json({ user });
99 }
100 case "POST": {
101 const user = yield* db
102 .insert(Users)
103 .values({
104 name: crypto.randomUUID(),
105 email: crypto.randomUUID(),
106 })
107 .returning();
108 return yield* HttpServerResponse.json({ user });
109 }
110 case "DELETE": {
111 const id = Number(path.split("/").pop());
112 if (Number.isNaN(id)) {
113 return yield* HttpServerResponse.json(
114 { error: "Invalid user ID" },
115 { status: 400 },
116 );
117 }
118 const [user] = yield* db
119 .delete(Users)
120 .where(eq(Users.id, id))
121 .returning();
122 return yield* HttpServerResponse.json({ user });
123 }
124 default: {
125 return yield* HttpServerResponse.json(
126 { error: "Method not allowed" },
127 { status: 405 },
128 );
129 }
130 }
131 }).pipe(
132 Effect.catch((cause: unknown) =>
133 HttpServerResponse.json(
134 { ok: false, error: String(cause) },
135 { status: 500 },
136 ),
137 ),
138 ),
139 };
140 }).pipe(Effect.provide(Fly.ConnectPostgresHttp)),
141) {}