@trifrost/core
Version:
Blazingly fast, runtime-agnostic server framework for modern edge and node environments
32 lines (31 loc) • 1.03 kB
JavaScript
export class Sliding {
#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 timestamps = (await this.#store.get(key)) || [];
/* Prune ONLY the first entry if it's outside the window */
if (timestamps.length && timestamps[0] < now - this.#window)
timestamps.shift();
/* Push the current timestamp */
timestamps.push(now);
/* Compute the reset time */
const reset = timestamps[0] + this.#window;
/* Avoid writes if we've already exceeded the limit */
if (timestamps.length <= limit) {
const ttl = reset - now;
await this.#store.set(key, timestamps, { ttl: Math.max(ttl, 1) });
}
return { amt: timestamps.length, reset };
}
async stop() {
await this.#store.stop();
}
}