@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 74 lines 2.88 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Drizzle from "@alchemy.run/drizzle/Postgres";
3 import { eq } 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 * as Layer from "effect/Layer";
8 import { relations, Widgets } from "./schema.ts";
9 import { Hyperdrive } from "./Stack.ts";
10
11 /**
12 * Worker fixture that binds a Cloudflare Hyperdrive (pointed at a
13 * Planetscale Postgres role) and exercises Drizzle's Effect-native
14 * client. Mirrors the cloudflare-planetscale-drizzle example but lives
15 * inside the package so the runtime path is covered by an integration
16 * test next to the resource it exercises.
17 */
18 export default class HyperdriveWorker extends Cloudflare.Worker<HyperdriveWorker>()(
19 "PlanetscaleHyperdriveWorker",
20 {
21 main: import.meta.url,
22 },
23 Effect.gen(function* () {
24 const conn = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
25 const db = yield* Drizzle.Postgres(conn.connectionString, { relations });
26
27 return {
28 fetch: Effect.gen(function* () {
29 const request = yield* HttpServerRequest;
30 const url = new URL(request.url, "http://x");
31
32 if (request.method === "GET" && url.pathname === "/hyperdrive") {
33 return yield* HttpServerResponse.json({
34 host: yield* conn.host,
35 port: yield* conn.port,
36 user: yield* conn.user,
37 database: yield* conn.database,
38 });
39 }
40
41 if (request.method === "GET" && url.pathname === "/widgets") {
42 const widgets = yield* db.select().from(Widgets);
43 return yield* HttpServerResponse.json({ widgets });
44 }
45
46 if (request.method === "POST" && url.pathname === "/widgets") {
47 const body = (yield* request.json) as { id: number; name: string };
48 const [inserted] = yield* db
49 .insert(Widgets)
50 .values({ id: body.id, name: body.name })
51 .onConflictDoUpdate({
52 target: Widgets.id,
53 set: { name: body.name },
54 })
55 .returning();
56 return yield* HttpServerResponse.json({ widget: inserted });
57 }
58
59 const idMatch = url.pathname.match(/^\/widgets\/(\d+)$/);
60 if (request.method === "DELETE" && idMatch) {
61 const id = Number(idMatch[1]);
62 const [deleted] = yield* db.delete(Widgets).where(eq(Widgets.id, id)).returning();
63 return yield* HttpServerResponse.json({ widget: deleted ?? null });
64 }
65
66 return HttpServerResponse.text("Not Found", { status: 404 });
67 }).pipe(
68 Effect.catch((cause: any) =>
69 HttpServerResponse.json({ ok: false, error: String(cause) }, { status: 500 }),
70 ),
71 ),
72 };
73 }).pipe(Effect.provide(Layer.mergeAll(Cloudflare.Hyperdrive.ConnectBinding))),
74 ) {}