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(); } }