| 1 | import { WorkerEntrypoint } from "cloudflare:workers"; |
| 2 | |
| 3 | const WORKER_ID = "hello-v1"; |
| 4 | const WORKER_MAIN = "worker.js"; |
| 5 | const WORKER_SOURCE = ` |
| 6 | export default { |
| 7 | fetch() { |
| 8 | console.log("hello from loaded code"); |
| 9 | return new Response("Hello from a Dynamic Worker!\\n"); |
| 10 | } |
| 11 | }; |
| 12 | `; |
| 13 | |
| 14 | export class DynamicWorkerTail extends WorkerEntrypoint { |
| 15 | tail(events) { |
| 16 | for (const event of events) { |
| 17 | for (const log of event.logs) { |
| 18 | console.log(`dynamic-worker-tail: ${log.message.join(" ")}`, { |
| 19 | workerId: this.ctx.props.workerId, |
| 20 | level: log.level, |
| 21 | }); |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | export default { |
| 28 | fetch(request, env, ctx) { |
| 29 | const worker = env.LOADER.get(WORKER_ID, () => ({ |
| 30 | mainModule: WORKER_MAIN, |
| 31 | modules: { [WORKER_MAIN]: WORKER_SOURCE }, |
| 32 | tails: [ |
| 33 | ctx.exports.DynamicWorkerTail({ |
| 34 | props: { workerId: WORKER_ID }, |
| 35 | }), |
| 36 | ], |
| 37 | })); |
| 38 | return worker.getEntrypoint().fetch(request); |
| 39 | }, |
| 40 | }; |