Diffinery

homeflare/celldpublic

46 lines · 1.3 KBRaw History
1import { 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.
5const 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
17export class Greeter extends WorkerEntrypoint {
18 greet(name) {
19 return `${this.ctx.props.greeting}, ${name}`;
20 }
21}
22
23export class Supervisor extends DurableObject {
24 fetch(request) {
25 const worker = this.env.LOADER.get("app-v1", () => ({
26 compatibilityDate: "2025-01-01",
27 mainModule: "app.js",
28 modules: { "app.js": CODE },
29 env: {
30 GREETER: this.ctx.exports.Greeter({
31 props: { greeting: "hello" },
32 }),
33 },
34 }));
35 const facet = this.ctx.facets.get("app", () => ({
36 class: worker.getDurableObjectClass("App"),
37 }));
38 return facet.fetch(request);
39 }
40}
41
42export default {
43 fetch(request, env) {
44 return env.SUPERVISOR.getByName("only").fetch(request);
45 },
46};