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 AWS from "@alchemy.run/aws"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import { LinkNotFound, Links, LinkStoreError, newCode, type Link } from "./Links.ts"; |
| 5 | |
| 6 | /** `Links` stored in a DynamoDB table that this Layer owns. Reads are strongly consistent. */ |
| 7 | export const LinksDynamo = Layer.effect( |
| 8 | Links, |
| 9 | Effect.gen(function* () { |
| 10 | const table = yield* AWS.DynamoDB.Table("LinksTable", { |
| 11 | partitionKey: "code", |
| 12 | attributes: { code: "S" }, |
| 13 | }); |
| 14 | const getItem = yield* AWS.DynamoDB.GetItem(table); |
| 15 | const putItem = yield* AWS.DynamoDB.PutItem(table); |
| 16 | const scan = yield* AWS.DynamoDB.Scan(table); |
| 17 | |
| 18 | const toItem = (link: Link) => ({ |
| 19 | code: { S: link.code }, |
| 20 | link: { S: JSON.stringify(link) }, |
| 21 | }); |
| 22 | const fromItem = (item: { link?: { S?: string } }) => JSON.parse(item.link!.S!) as Link; |
| 23 | |
| 24 | const get = Effect.fn(function* (code: string) { |
| 25 | const { Item } = yield* getItem({ Key: { code: { S: code } }, ConsistentRead: true }); |
| 26 | if (!Item) return yield* new LinkNotFound({ code }); |
| 27 | return fromItem(Item); |
| 28 | }); |
| 29 | |
| 30 | const storeError = (cause: unknown) => new LinkStoreError({ cause }); |
| 31 | |
| 32 | return { |
| 33 | create: Effect.fn(function* (url: string) { |
| 34 | const link: Link = { code: newCode(), url, createdAt: Date.now() }; |
| 35 | yield* putItem({ Item: toItem(link) }); |
| 36 | return link; |
| 37 | }, Effect.mapError(storeError)), |
| 38 | get: (code: string) => |
| 39 | get(code).pipe( |
| 40 | Effect.catchIf( |
| 41 | (error) => error._tag !== "LinkNotFound", |
| 42 | (cause) => Effect.fail(storeError(cause)), |
| 43 | ), |
| 44 | ), |
| 45 | list: Effect.fn(function* () { |
| 46 | const { Items } = yield* scan({ ConsistentRead: true }); |
| 47 | return (Items ?? []).map(fromItem).sort((a, b) => b.createdAt - a.createdAt); |
| 48 | }, Effect.mapError(storeError)), |
| 49 | setPreview: (code: string, preview: Link["preview"] & {}) => |
| 50 | get(code).pipe( |
| 51 | Effect.flatMap((link) => putItem({ Item: toItem({ ...link, preview }) })), |
| 52 | Effect.asVoid, |
| 53 | Effect.catchIf( |
| 54 | (error) => error._tag !== "LinkNotFound", |
| 55 | (cause) => Effect.fail(storeError(cause)), |
| 56 | ), |
| 57 | ), |
| 58 | }; |
| 59 | }), |
| 60 | ).pipe( |
| 61 | Layer.provide( |
| 62 | Layer.mergeAll(AWS.DynamoDB.GetItemHttp, AWS.DynamoDB.PutItemHttp, AWS.DynamoDB.ScanHttp), |
| 63 | ), |
| 64 | ); |