| 1 | import { WorkflowEntrypoint } from "cloudflare:workers"; |
| 2 | |
| 3 | export class ReportBuilder extends WorkflowEntrypoint { |
| 4 | async run(event, step) { |
| 5 | // A completed step returns its stored result when the Workflow resumes. |
| 6 | return await step.do("build report", async () => { |
| 7 | const response = await fetch(event.payload.url); |
| 8 | if (!response.ok) throw new Error(`source answered ${response.status}`); |
| 9 | const text = await response.text(); |
| 10 | return { bytes: text.length, lines: text.split("\n").length }; |
| 11 | }); |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | export default { |
| 16 | async fetch(request, env) { |
| 17 | const url = new URL(request.url); |
| 18 | const id = url.searchParams.get("id"); |
| 19 | |
| 20 | if (url.pathname === "/create") { |
| 21 | const instance = await env.REPORTS.create({ |
| 22 | params: { url: url.searchParams.get("url") ?? "https://example.com" }, |
| 23 | }); |
| 24 | return Response.json({ id: instance.id }); |
| 25 | } |
| 26 | |
| 27 | if (url.pathname === "/status" && id) { |
| 28 | const instance = await env.REPORTS.get(id); |
| 29 | return Response.json(await instance.status()); |
| 30 | } |
| 31 | |
| 32 | return new Response("Use /create?url=URL or /status?id=ID.", { |
| 33 | status: 404, |
| 34 | }); |
| 35 | }, |
| 36 | }; |