@trifrost/core
Version:
Blazingly fast, runtime-agnostic server framework for modern edge and node environments
35 lines (34 loc) • 901 B
JavaScript
export class Fixed {
#window;
#store;
constructor(window = 60, store) {
this.#window = window;
this.#store = store;
}
get store() {
return this.#store;
}
async consume(key, limit) {
const now = Math.floor(Date.now() / 1000);
const record = await this.#store.get(key);
let amt;
let reset;
if (!record || record.reset <= now) {
amt = 1;
reset = now + this.#window;
}
else {
amt = record.amt + 1;
reset = record.reset;
}
/* Avoid writes if we've already exceeded the limit */
if (amt <= limit) {
const ttl = reset - now;
await this.#store.set(key, { amt, reset }, { ttl: Math.max(ttl, 1) });
}
return { amt, reset };
}
async stop() {
await this.#store.stop();
}
}