| 1 | import { DurableObject, WorkerEntrypoint } from "cloudflare:workers"; |
| 2 | |
| 3 | // The code of the facet. A real application would load it from a bundle, |
| 4 | // a database, or a request; here it is a string so the example is one file. |
| 5 | const CODE = ` |
| 6 | import { DurableObject } from "cloudflare:workers"; |
| 7 | export class App extends DurableObject { |
| 8 | async fetch() { |
| 9 | const n = this.ctx.storage.kv.get("n") ?? 0; |
| 10 | this.ctx.storage.kv.put("n", n + 1); |
| 11 | const greeting = await this.env.GREETER.greet("facet"); |
| 12 | return new Response(String(n) + ":" + greeting); |
| 13 | } |
| 14 | } |
| 15 | `; |
| 16 | |
| 17 | export class Greeter extends WorkerEntrypoint { |
| 18 | greet(name) { |
| 19 | return `${this.ctx.props.greeting}, ${name}`; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | export class Supervisor extends DurableObject { |
| 24 | fetch(request) { |
| 25 | const worker = this.env.LOADER.get("app-v1", () => ({ |
| 26 | mainModule: "app.js", |
| 27 | modules: { "app.js": CODE }, |
| 28 | env: { |
| 29 | GREETER: this.ctx.exports.Greeter({ |
| 30 | props: { greeting: "hello" }, |
| 31 | }), |
| 32 | }, |
| 33 | })); |
| 34 | const facet = this.ctx.facets.get("app", () => ({ |
| 35 | class: worker.getDurableObjectClass("App"), |
| 36 | })); |
| 37 | return facet.fetch(request); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export default { |
| 42 | fetch(request, env) { |
| 43 | return env.SUPERVISOR.getByName("only").fetch(request); |
| 44 | }, |
| 45 | }; |