| 1 | // Reads the request body — the gap that make_request left open. Routes by path |
| 2 | // so the body must also survive a cross-node proxy hop. Plain DO code. |
| 3 | export class Echo { |
| 4 | constructor(state, env) { this.state = state; } |
| 5 | async fetch(request) { |
| 6 | if (request.method === "POST" || request.method === "PUT") { |
| 7 | const data = await request.json(); |
| 8 | let sum = (await this.state.storage.get("sum")) ?? 0; |
| 9 | sum += data.n ?? 0; |
| 10 | await this.state.storage.put("sum", sum); |
| 11 | return new Response(JSON.stringify({ echoed: data, sum })); |
| 12 | } |
| 13 | const text = await request.text(); |
| 14 | return new Response(JSON.stringify({ method: request.method, bodyLen: text.length })); |
| 15 | } |
| 16 | } |
| 17 | export default { |
| 18 | async fetch(request, env) { |
| 19 | const name = new URL(request.url).pathname.slice(1) || "default"; |
| 20 | return env.ECHO.get(env.ECHO.idFromName(name)).fetch(request); |
| 21 | } |
| 22 | }; |