summaryrefslogtreecommitdiff
path: root/src/pages/api
diff options
context:
space:
mode:
Diffstat (limited to 'src/pages/api')
-rw-r--r--src/pages/api/counter.ts59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/pages/api/counter.ts b/src/pages/api/counter.ts
new file mode 100644
index 0000000..152dc54
--- /dev/null
+++ b/src/pages/api/counter.ts
@@ -0,0 +1,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' }
+ });
+}; \ No newline at end of file