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 type * as Alchemy from "alchemy"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Data from "effect/Data"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as SqlClient from "effect/sql/SqlClient"; |
| 7 | import { LinkNotFound, newCode, type Link } from "./Link.ts"; |
| 8 | |
| 9 | export class LinkStoreError extends Data.TaggedError("LinkStoreError")<{ cause: unknown }> {} |
| 10 | |
| 11 | /** Where links live. The Worker depends on this contract, never on a database. */ |
| 12 | export class Links extends Context.Service< |
| 13 | Links, |
| 14 | { |
| 15 | create(url: string): Effect.Effect<Link, LinkStoreError, Alchemy.RuntimeContext>; |
| 16 | get(code: string): Effect.Effect<Link, LinkNotFound | LinkStoreError, Alchemy.RuntimeContext>; |
| 17 | list(): Effect.Effect<readonly Link[], LinkStoreError, Alchemy.RuntimeContext>; |
| 18 | } |
| 19 | >()("Links") {} |
| 20 | |
| 21 | /** `Links` over any SQL database: D1, Postgres, … whatever provides a `SqlClient`. */ |
| 22 | export const LinksSql = Layer.effect( |
| 23 | Links, |
| 24 | Effect.gen(function* () { |
| 25 | const sql = yield* SqlClient.SqlClient; |
| 26 | const storeError = (cause: unknown) => new LinkStoreError({ cause }); |
| 27 | |
| 28 | return { |
| 29 | create: (url: string) => |
| 30 | Effect.gen(function* () { |
| 31 | yield* Effect.annotateCurrentSpan({ url }); |
| 32 | const link = { code: newCode(), url, createdAt: new Date().toISOString() }; |
| 33 | yield* sql` |
| 34 | INSERT INTO links (code, url, created_at) |
| 35 | VALUES (${link.code}, ${link.url}, ${link.createdAt})`; |
| 36 | return link; |
| 37 | }).pipe(Effect.mapError(storeError), Effect.withSpan("links.create")), |
| 38 | get: (code: string) => |
| 39 | Effect.gen(function* () { |
| 40 | yield* Effect.annotateCurrentSpan({ code }); |
| 41 | const [link] = yield* sql<Link>` |
| 42 | SELECT code, url, created_at AS "createdAt" FROM links WHERE code = ${code}`; |
| 43 | if (!link) return yield* new LinkNotFound({ code }); |
| 44 | return link; |
| 45 | }).pipe( |
| 46 | Effect.catchTag("SqlError", (cause) => Effect.fail(storeError(cause))), |
| 47 | Effect.withSpan("links.get"), |
| 48 | ), |
| 49 | list: () => |
| 50 | sql<Link>` |
| 51 | SELECT code, url, created_at AS "createdAt" FROM links |
| 52 | ORDER BY created_at DESC`.pipe( |
| 53 | Effect.mapError(storeError), |
| 54 | Effect.withSpan("links.list"), |
| 55 | ), |
| 56 | }; |
| 57 | }), |
| 58 | ); |