The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as Http from "alchemy/Http"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 5 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import { Order, OrderNotFound, OrdersApi, Product, ProductNotFound } from "./Api.ts"; |
| 8 | import { Catalog, HOSTNAME, OrderBook } from "./Store.ts"; |
| 9 | |
| 10 | /** `/orders/*` — reads the catalog, reads and writes orders. */ |
| 11 | export default class Orders extends Cloudflare.Worker<Orders>()( |
| 12 | "Orders", |
| 13 | { |
| 14 | main: import.meta.url, |
| 15 | routes: [{ pattern: `${HOSTNAME}/orders*` }], |
| 16 | }, |
| 17 | Effect.gen(function* () { |
| 18 | const catalog = yield* Cloudflare.KV.ReadNamespace(Catalog); |
| 19 | const orders = yield* Cloudflare.KV.ReadWriteNamespace(OrderBook); |
| 20 | |
| 21 | return { |
| 22 | fetch: yield* HttpRouter.toHttpEffect( |
| 23 | HttpApiBuilder.layer(OrdersApi).pipe( |
| 24 | Layer.provide(Http.Platform), |
| 25 | Layer.provide( |
| 26 | HttpApiBuilder.group(OrdersApi, "orders", (handlers) => |
| 27 | handlers |
| 28 | .handle("create", ({ payload }) => |
| 29 | Effect.gen(function* () { |
| 30 | const product = yield* catalog |
| 31 | .get<Product>(payload.productId, "json") |
| 32 | .pipe(Effect.orDie); |
| 33 | if (!product) { |
| 34 | return yield* new ProductNotFound({ id: payload.productId }); |
| 35 | } |
| 36 | const order = new Order({ |
| 37 | id: crypto.randomUUID(), |
| 38 | productId: product.id, |
| 39 | quantity: payload.quantity, |
| 40 | total: product.price * payload.quantity, |
| 41 | }); |
| 42 | yield* orders.put(order.id, JSON.stringify(order)).pipe(Effect.orDie); |
| 43 | return order; |
| 44 | }), |
| 45 | ) |
| 46 | .handle("get", ({ params }) => |
| 47 | orders.get<Order>(params.id, "json").pipe( |
| 48 | Effect.orDie, |
| 49 | Effect.flatMap((order) => |
| 50 | order |
| 51 | ? Effect.succeed(new Order(order)) |
| 52 | : Effect.fail(new OrderNotFound({ id: params.id })), |
| 53 | ), |
| 54 | ), |
| 55 | ), |
| 56 | ), |
| 57 | ), |
| 58 | ), |
| 59 | ), |
| 60 | }; |
| 61 | }).pipe( |
| 62 | Effect.provide( |
| 63 | Layer.mergeAll(Cloudflare.KV.ReadNamespaceBinding, Cloudflare.KV.ReadWriteNamespaceBinding), |
| 64 | ), |
| 65 | ), |
| 66 | ) {} |