Skip to content

Commit

Permalink
fix(cf): corrected DO class
Browse files Browse the repository at this point in the history
  • Loading branch information
MathurAditya724 committed Sep 2, 2024
1 parent 9333a58 commit 4575dd3
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions packages/cloudflare/src/stores/DurableObjectClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ClientRateLimitInfo>("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();
}
}

0 comments on commit 4575dd3

Please sign in to comment.