1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import type { SSRManifest } from 'astro';
import { App } from 'astro/app';
import { handle } from '@astrojs/cloudflare/handler';
import { DurableObject } from 'cloudflare:workers';
interface Env {
COUNTER_DO: DurableObjectNamespace;
}
class CounterDurableObject extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const pathname = url.pathname;
if (pathname === '/increment') {
const currentValue = (await this.ctx.storage.get<number>('counter')) || 0;
const newValue = currentValue + 1;
await this.ctx.storage.put('counter', newValue);
return new Response(JSON.stringify({
counter: newValue,
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
}
if (pathname === '/get') {
const currentValue = (await this.ctx.storage.get<number>('counter')) || 0;
return new Response(JSON.stringify({
counter: currentValue,
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
}
if (pathname === '/reset') {
await this.ctx.storage.put('counter', 0);
return new Response(JSON.stringify({
counter: 0,
message: 'Counter reset',
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Not found', { status: 404 });
}
}
export function createExports(manifest: SSRManifest) {
const app = new App(manifest);
return {
default: {
async fetch(request, env, ctx) {
return handle(manifest, app, request, env, ctx);
}
} satisfies ExportedHandler<Env>,
CounterDurableObject: CounterDurableObject,
};
}
|