| 1 | export class Echo { |
| 2 | constructor(state, env) { |
| 3 | this.state = state; |
| 4 | } |
| 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 Response.json({ echoed: data, sum }); |
| 12 | } |
| 13 | const text = await request.text(); |
| 14 | return Response.json({ 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 | }; |