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