@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, 06:00 UTC

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