UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

39 lines (38 loc) 1.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Fixed = void 0; 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(); } } exports.Fixed = Fixed;