blob: 152dc5420445c0e3f1e37836071609cdfdde1c27 (
plain)
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
|
import type { APIRoute } from 'astro';
interface Env {
COUNTER_DO: DurableObjectNamespace;
}
export const GET: APIRoute = async ({ request }) => {
const env = request.cf?.env as Env;
if (!env?.COUNTER_DO) {
return new Response(JSON.stringify({ error: 'Durable Object not available' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
const id = env.COUNTER_DO.idFromName('global-counter');
const stub = env.COUNTER_DO.get(id);
const response = await stub.fetch(new Request('https://counter.do/get'));
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
};
export const POST: APIRoute = async ({ request }) => {
const env = request.cf?.env as Env;
if (!env?.COUNTER_DO) {
return new Response(JSON.stringify({ error: 'Durable Object not available' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
const url = new URL(request.url);
const action = url.searchParams.get('action') || 'increment';
const id = env.COUNTER_DO.idFromName('global-counter');
const stub = env.COUNTER_DO.get(id);
let doRequest: Request;
switch (action) {
case 'reset':
doRequest = new Request('https://counter.do/reset');
break;
case 'increment':
default:
doRequest = new Request('https://counter.do/increment');
break;
}
const response = await stub.fetch(doRequest);
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
};
|