1import { DurableObject } from "cloudflare:workers";
2
3const COUNT_KEY = "count";
4
5type CounterStub = {
6 get(): Promise<number>;
7 increment(): Promise<number>;
8 reset(): Promise<void>;
9};
10
11type Env = {
12 ASSETS: {
13 fetch(request: Request): Promise<Response>;
14 };
15 Counter: {
16 getByName(name: string): CounterStub;
17 };
18};
19
20export class Counter extends DurableObject {
21 async get() {
22 return (await this.ctx.storage.get<number>(COUNT_KEY)) ?? 0;
23 }
24
25 async increment() {
26 const next = (await this.get()) + 1;
27 await this.ctx.storage.put(COUNT_KEY, next);
28 return next;
29 }
30
31 async reset() {
32 await this.ctx.storage.delete(COUNT_KEY);
33 }
34}
35
36export default {
37 async fetch(request: Request, env: Env): Promise<Response> {
38 const url = new URL(request.url);
39 const counter = env.Counter.getByName("vite-do-fixture");
40
41 if (url.pathname === "/api/count") {
42 return Response.json({ count: await counter.increment() });
43 }
44
45 if (url.pathname === "/api/current") {
46 return Response.json({ count: await counter.get() });
47 }
48
49 if (url.pathname === "/api/reset") {
50 await counter.reset();
51 return Response.json({ ok: true });
52 }
53
54 return env.ASSETS.fetch(request);
55 },
56};