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

main
ts 66 lines 2.47 KB
Raw
1 import * as Drizzle from "@alchemy.run/drizzle/Postgres";
2 import * as Fly from "@alchemy.run/fly";
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 { API_PORT, Db } 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 * Effect HTTP API on a Fly Machine. Binds Managed Postgres via
21 * {@link Fly.ConnectPostgres} and serves `/notes` for the Vite SPA.
22 */
23 export default class Api extends Fly.Service<Api>()(
24 "Api",
25 {
26 main: import.meta.url,
27 port: API_PORT,
28 guest: { cpuKind: "shared", cpus: 1, memoryMb: 256 },
29 },
30 Effect.gen(function* () {
31 const conn = yield* Fly.ConnectPostgres(Db);
32 const db = yield* Drizzle.Postgres(conn.connectionString);
33
34 return {
35 fetch: Effect.gen(function* () {
36 const request = yield* HttpServerRequest;
37 const path = new URL(request.url, "http://service").pathname;
38 if (request.method === "OPTIONS") {
39 return yield* json({}, 204);
40 }
41 yield* db.execute(sql.raw(ENSURE_NOTES_SQL));
42 if (path === "/health") {
43 return yield* json({ ok: true });
44 }
45 if (path === "/notes" && request.method === "GET") {
46 const notes = yield* db.select().from(Notes).orderBy(desc(Notes.createdAt));
47 return yield* json({ notes });
48 }
49 if (path === "/notes" && request.method === "POST") {
50 const raw = yield* request.text.pipe(Effect.orDie);
51 const payload = JSON.parse(raw) as { body?: unknown };
52 const body = typeof payload.body === "string" ? payload.body.trim() : "";
53 if (body.length === 0) {
54 return yield* json({ error: "body required" }, 400);
55 }
56 const [note] = yield* db.insert(Notes).values({ body }).returning();
57 return yield* json({ note }, 201);
58 }
59 return yield* json({ error: "not found" }, 404);
60 }).pipe(
61 Effect.catch((cause: unknown) => json({ ok: false, error: String(cause) }, 500)),
62 Effect.orDie,
63 ),
64 };
65 }).pipe(Effect.provide(Fly.ConnectPostgresHttp)),
66 ) {}