@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 71 lines 2.56 KB
Raw
1 import * as Drizzle from "@alchemy.run/drizzle/Postgres";
2 import * as Hetzner from "@alchemy.run/hetzner";
3 import { desc, sql } from "drizzle-orm";
4 import * as Config from "effect/Config";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import { ENSURE_NOTES_SQL, Notes } from "./schema.ts";
9 import { API_PORT, Box, NeonBranch } from "./shared.ts";
10
11 const cors = {
12 "access-control-allow-origin": "*",
13 "access-control-allow-methods": "GET,POST,OPTIONS",
14 "access-control-allow-headers": "content-type",
15 };
16
17 const json = (value: unknown, status = 200) =>
18 HttpServerResponse.json(value, { status, headers: cors });
19
20 /**
21 * Effect HTTP API on the shared Hetzner Server. Reads `DATABASE_URL`
22 * (the Neon branch URI) and serves `/notes` for the Vite SPA.
23 */
24 export default class Api extends Hetzner.Service<Api>()(
25 "Api",
26 Effect.gen(function* () {
27 const server = yield* Box;
28 const branch = yield* NeonBranch;
29 return {
30 server,
31 main: import.meta.url,
32 port: API_PORT,
33 env: {
34 DATABASE_URL: branch.connectionUri,
35 },
36 };
37 }),
38 Effect.succeed({
39 fetch: Effect.gen(function* () {
40 const databaseUrl = yield* Config.Redacted("DATABASE_URL");
41 const db = yield* Drizzle.Postgres(Effect.succeed(databaseUrl));
42 const request = yield* HttpServerRequest;
43 const path = new URL(request.url, "http://service").pathname;
44 if (request.method === "OPTIONS") {
45 return yield* json({}, 204);
46 }
47 yield* db.execute(sql.raw(ENSURE_NOTES_SQL));
48 if (path === "/health") {
49 return yield* json({ ok: true });
50 }
51 if (path === "/notes" && request.method === "GET") {
52 const notes = yield* db.select().from(Notes).orderBy(desc(Notes.createdAt));
53 return yield* json({ notes });
54 }
55 if (path === "/notes" && request.method === "POST") {
56 const raw = yield* request.text.pipe(Effect.orDie);
57 const payload = JSON.parse(raw) as { body?: unknown };
58 const body = typeof payload.body === "string" ? payload.body.trim() : "";
59 if (body.length === 0) {
60 return yield* json({ error: "body required" }, 400);
61 }
62 const [note] = yield* db.insert(Notes).values({ body }).returning();
63 return yield* json({ note }, 201);
64 }
65 return yield* json({ error: "not found" }, 404);
66 }).pipe(
67 Effect.catch((cause: unknown) => json({ ok: false, error: String(cause) }, 500)),
68 Effect.orDie,
69 ),
70 }),
71 ) {}