| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | |
| 3 | export class Counter extends DurableObject { |
| 4 | async increment(amount) { |
| 5 | const count = ((await this.ctx.storage.get("count")) ?? 0) + amount; |
| 6 | await this.ctx.storage.put("count", count); |
| 7 | return count; |
| 8 | } |
| 9 | |
| 10 | async value() { |
| 11 | return (await this.ctx.storage.get("count")) ?? 0; |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | export default { |
| 16 | async fetch(request, env, ctx) { |
| 17 | const counter = env.COUNTER.getByName("counter"); |
| 18 | if (request.method === "POST") { |
| 19 | return Response.json({ count: await counter.increment(1) }); |
| 20 | } |
| 21 | return Response.json({ count: await counter.value() }); |
| 22 | }, |
| 23 | }; |