| 1 | export class Agent { |
| 2 | constructor(state, env) { |
| 3 | this.state = state; |
| 4 | } |
| 5 | async fetch(request) { |
| 6 | const url = new URL(request.url); |
| 7 | if (url.pathname === "/arm") { |
| 8 | await this.state.storage.setAlarm(Date.now() + 2000); |
| 9 | return Response.json({ |
| 10 | armed: true, |
| 11 | at: await this.state.storage.getAlarm(), |
| 12 | }); |
| 13 | } |
| 14 | const fires = (await this.state.storage.get("fires")) ?? 0; |
| 15 | return Response.json({ |
| 16 | fires, |
| 17 | pendingAlarm: await this.state.storage.getAlarm(), |
| 18 | }); |
| 19 | } |
| 20 | async alarm(info) { |
| 21 | const fires = (await this.state.storage.get("fires")) ?? 0; |
| 22 | await this.state.storage.put("fires", fires + 1); |
| 23 | await this.state.storage.put("lastRetry", info.retryCount); |
| 24 | } |
| 25 | } |
| 26 | export default { |
| 27 | async fetch(request, env) { |
| 28 | const id = env.AGENT.idFromName("a1"); |
| 29 | return env.AGENT.get(id).fetch(request); |
| 30 | }, |
| 31 | }; |