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
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as PrismaPostgres from "@alchemy.run/prisma/ORM/Postgres"; |
| 3 | import { makeSchemas } from "@alchemy.run/prisma/ORM/Schema"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as HttpServerRequest from "effect/http/HttpServerRequest"; |
| 6 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import { Hyperdrive } from "./Db.ts"; |
| 9 | import { contract } from "./prisma/contract.ts"; |
| 10 | |
| 11 | const schemas = makeSchemas(contract); |
| 12 | |
| 13 | export default class Api extends Cloudflare.Worker<Api>()( |
| 14 | "Api", |
| 15 | { |
| 16 | main: import.meta.url, |
| 17 | }, |
| 18 | Effect.gen(function* () { |
| 19 | const conn = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive); |
| 20 | const db = yield* PrismaPostgres.Postgres(conn.connectionString, { |
| 21 | contract, |
| 22 | }); |
| 23 | |
| 24 | return { |
| 25 | fetch: Effect.gen(function* () { |
| 26 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 27 | switch (request.method) { |
| 28 | case "GET": { |
| 29 | if (request.url === "/") { |
| 30 | const users = yield* db.orm.public.User.all(); |
| 31 | return yield* HttpServerResponse.json({ users }); |
| 32 | } |
| 33 | const id = request.url.split("/").pop() ?? ""; |
| 34 | const user = yield* db.orm.public.User.where({ id }).include("posts").first(); |
| 35 | return yield* HttpServerResponse.json({ user }); |
| 36 | } |
| 37 | case "POST": { |
| 38 | const values = yield* Effect.sync(() => ({ |
| 39 | name: crypto.randomUUID(), |
| 40 | email: crypto.randomUUID(), |
| 41 | })); |
| 42 | const row = yield* db.orm.public.User.create(values); |
| 43 | const user = yield* Schema.decodeUnknownEffect(schemas.public.User)(row); |
| 44 | return yield* HttpServerResponse.json({ user }); |
| 45 | } |
| 46 | case "DELETE": { |
| 47 | const id = request.url.split("/").pop() ?? ""; |
| 48 | const user = yield* db.orm.public.User.where({ id }).delete(); |
| 49 | return yield* HttpServerResponse.json({ user }); |
| 50 | } |
| 51 | default: { |
| 52 | return yield* HttpServerResponse.json({ error: "Method not allowed" }, { status: 405 }); |
| 53 | } |
| 54 | } |
| 55 | }).pipe( |
| 56 | Effect.catch((cause) => |
| 57 | HttpServerResponse.json({ ok: false, error: cause._tag }, { status: 500 }), |
| 58 | ), |
| 59 | ), |
| 60 | }; |
| 61 | }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)), |
| 62 | ) {} |