|
| 1 | +# Worker Entrypoint |
| 2 | + |
| 3 | +The Worker entrypoint usually exports: |
| 4 | + |
| 5 | +- a default `fetch` handler |
| 6 | +- each Durable Object class as a named export |
| 7 | + |
| 8 | +`Worker.make(...)` supplies the Worker-side runtime for ordinary HTTP handling. `WorkerdActorNamespace` separately |
| 9 | +manages the Durable Object runtime for actor messages. |
| 10 | + |
| 11 | +## Build the entrypoint |
| 12 | + |
| 13 | +```ts |
| 14 | +// main.ts |
| 15 | +import { Effect, Layer } from "effect" |
| 16 | +import { Assets, Worker } from "effect-workerd" |
| 17 | +import { HttpRouter, HttpServerResponse } from "effect/unstable/http" |
| 18 | + |
| 19 | +import * as GameState from "./Games.ts" |
| 20 | +import { KvLive } from "./KvLive.ts" |
| 21 | +import { TicTacToeNamespace } from "./TicTacToeNamespace.ts" |
| 22 | + |
| 23 | +export { TicTacToeNamespace } |
| 24 | + |
| 25 | +const ApiLive = Layer.mergeAll( |
| 26 | + HttpRouter.add("GET", "/", Effect.succeed(HttpServerResponse.text("ok"))), |
| 27 | + HttpRouter.add( |
| 28 | + "GET", |
| 29 | + "/play", |
| 30 | + Effect.gen(function* () { |
| 31 | + const { gameId, player } = yield* GameState.init |
| 32 | + return yield* TicTacToeNamespace.upgrade(gameId, { player }) |
| 33 | + }), |
| 34 | + ), |
| 35 | + HttpRouter.cors({ |
| 36 | + allowedHeaders: ["*"], |
| 37 | + allowedMethods: ["*"], |
| 38 | + allowedOrigins: ["*"], |
| 39 | + }), |
| 40 | + HttpRouter.add("*", "/*", Assets.forward), |
| 41 | +) |
| 42 | + |
| 43 | +export default Worker.make({ |
| 44 | + handler: ApiLive.pipe(HttpRouter.toHttpEffect, Effect.flatten), |
| 45 | + prelude: Layer.mergeAll(KvLive, TicTacToeNamespace.layer("TICTACTOE"), Assets.layer("ASSETS")), |
| 46 | +}) |
| 47 | +``` |
| 48 | + |
| 49 | +## Things to notice |
| 50 | + |
| 51 | +- `HttpRouter.add(method, path, effect)` mounts a single route. |
| 52 | +- `HttpRouter.cors(...)` wires up CORS for every route in the router. |
| 53 | +- `HttpRouter.add("*", "/*", Assets.forward)` falls through to the Cloudflare Assets binding for unmatched requests. |
| 54 | +- `Worker.make({ handler, prelude })` produces the Worker `fetch` export. |
| 55 | +- The Durable Object class must be re-exported from the Worker entrypoint. |
0 commit comments