From 4575dd3cd61c1a6075d3283b3632284db9890000 Mon Sep 17 00:00:00 2001 From: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> Date: Tue, 3 Sep 2024 00:17:55 +0530 Subject: [PATCH] fix(cf): corrected DO class --- .../src/stores/DurableObjectClass.ts | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/packages/cloudflare/src/stores/DurableObjectClass.ts b/packages/cloudflare/src/stores/DurableObjectClass.ts index cba652c..2cc72ae 100644 --- a/packages/cloudflare/src/stores/DurableObjectClass.ts +++ b/packages/cloudflare/src/stores/DurableObjectClass.ts @@ -6,34 +6,35 @@ const initialState: ClientRateLimitInfo = { }; export class DurableObjectRateLimiter extends DurableObject { - payload: ClientRateLimitInfo; - constructor(ctx: DurableObjectState, env: unknown) { - super(ctx, env); - this.payload = initialState; - } - async update(hits: number, windowMs: number) { + let payload = + (await this.ctx.storage.get("value")) || + initialState; + // Updating the payload - const resetTime = this.payload.resetTime ?? new Date(Date.now() + windowMs); - this.payload = { - totalHits: this.payload.totalHits + hits, + const resetTime = new Date(payload.resetTime ?? Date.now() + windowMs); + + payload = { + totalHits: payload.totalHits + hits, resetTime, }; // Updating the alarm const currentAlarm = await this.ctx.storage.getAlarm(); if (currentAlarm == null) { - this.ctx.storage.setAlarm(resetTime.getMilliseconds()); + this.ctx.storage.setAlarm(resetTime.getTime()); } - return this.payload; + await this.ctx.storage.put("value", payload); + + return payload; } - reset() { - this.payload = initialState; + async reset() { + await this.ctx.storage.put("value", initialState); } override async alarm() { - this.reset(); + await this.reset(); } }