From 9787d6ef4b59ab5cd514b5b3f45fa838a6eddb8c Mon Sep 17 00:00:00 2001 From: Petter Rasmussen Date: Sun, 21 Jul 2024 20:31:05 +0200 Subject: [PATCH] Use DO fetch --- glot_cloudflare/functions/api/run.ts | 3 ++- glot_cloudflare_rate_limiter/src/rate_limiter.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/glot_cloudflare/functions/api/run.ts b/glot_cloudflare/functions/api/run.ts index a0c043e..86817b3 100644 --- a/glot_cloudflare/functions/api/run.ts +++ b/glot_cloudflare/functions/api/run.ts @@ -19,7 +19,8 @@ export const onRequestPost: PagesFunction = async (context) const id = context.env.RATE_LIMITER.idFromName(ip); const stub = context.env.RATE_LIMITER.get(id); - const stats = stub.increment({ maxRequests: 10, periodDuration: 60 * 1000 }); + const response = await stub.fetch(context.request); + const stats = await response.text(); console.log(stats) diff --git a/glot_cloudflare_rate_limiter/src/rate_limiter.ts b/glot_cloudflare_rate_limiter/src/rate_limiter.ts index fe5a9b5..e5afa2c 100644 --- a/glot_cloudflare_rate_limiter/src/rate_limiter.ts +++ b/glot_cloudflare_rate_limiter/src/rate_limiter.ts @@ -16,6 +16,11 @@ export class RateLimiter extends DurableObject { private startTimestamp: number = 0; private requestCount: number = 0; + async fetch(request: Request): Promise { + const stats = await this.increment({ maxRequests: 10, periodDuration: 60 * 1000 }); + return new Response(JSON.stringify(stats), { status: 200 }); + } + async increment(config: RateLimitConfig): Promise { const now = Date.now(); const elapsedTime = now - this.startTimestamp;