The best way to control Claude Code, Codex and more from any computer or phone
| 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 | // #region service |
| 10 | // #region storeError |
| 11 | export class LinkStoreError extends Data.TaggedError("LinkStoreError")<{ cause: unknown }> {} |
| 12 | |
| 13 | // #endregion storeError |
| 14 | export class Links extends Context.Service< |
| 15 | Links, |
| 16 | { |
| 17 | create(url: string): Effect.Effect<Link, LinkStoreError, Alchemy.RuntimeContext>; |
| 18 | // #region get |
| 19 | get(code: string): Effect.Effect<Link, LinkNotFound | LinkStoreError, Alchemy.RuntimeContext>; |
| 20 | // #endregion get |
| 21 | // #region list |
| 22 | list(): Effect.Effect<readonly Link[], LinkStoreError, Alchemy.RuntimeContext>; |
| 23 | // #endregion list |
| 24 | } |
| 25 | >()("Links") {} |
| 26 | // #endregion service |
| 27 | |
| 28 | /** `Links` over any SQL database: D1, Postgres, … whatever provides a `SqlClient`. */ |
| 29 | export const LinksSql = Layer.effect( |
| 30 | Links, |
| 31 | Effect.gen(function* () { |
| 32 | const sql = yield* SqlClient.SqlClient; |
| 33 | const storeError = (cause: unknown) => new LinkStoreError({ cause }); |
| 34 | |
| 35 | return { |
| 36 | create: (url: string) => |
| 37 | Effect.gen(function* () { |
| 38 | const link = { code: newCode(), url, createdAt: new Date().toISOString() }; |
| 39 | yield* sql` |
| 40 | INSERT INTO links (code, url, created_at) |
| 41 | VALUES (${link.code}, ${link.url}, ${link.createdAt})`; |
| 42 | return link; |
| 43 | }).pipe(Effect.mapError(storeError)), |
| 44 | get: (code: string) => |
| 45 | Effect.gen(function* () { |
| 46 | const [link] = yield* sql<Link>` |
| 47 | SELECT code, url, created_at AS "createdAt" FROM links WHERE code = ${code}`; |
| 48 | if (!link) return yield* new LinkNotFound({ code }); |
| 49 | return link; |
| 50 | }).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(storeError(cause)))), |
| 51 | list: () => |
| 52 | sql<Link>` |
| 53 | SELECT code, url, created_at AS "createdAt" FROM links |
| 54 | ORDER BY created_at DESC`.pipe(Effect.mapError(storeError)), |
| 55 | }; |
| 56 | }), |
| 57 | ); |