@da440dil/js-counter
Version:
Distributed rate limiting using Redis
34 lines (33 loc) • 1.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Counter = exports.Algorithm = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const js_redis_script_1 = require("@da440dil/js-redis-script");
const fwsrc = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../fixedwindow.lua')).toString();
const swsrc = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../slidingwindow.lua')).toString();
/** One of algorithms: 1 stands for the fixed window algorithm, 2 stands for the sliding window algorithm. */
exports.Algorithm = {
/** Fixed window. */
Fixed: 1,
/** Sliding window. */
Sliding: 2
};
/** Implements distributed counter. */
class Counter {
constructor(client, size, limit, algorithm) {
this.size = size;
this.limit = limit;
this.script = (0, js_redis_script_1.createScript)(client, algorithm === exports.Algorithm.Sliding ? swsrc : fwsrc, 1);
}
/**
* Increments key value by specified value.
* @param key The key to be incremented.
* @param value The value the key value to be incremented by.
*/
async count(key, value) {
const v = await this.script.run(key, value, this.size, this.limit);
return { ok: v[0] === 1, counter: v[1], remainder: this.limit - v[1], ttl: v[2] };
}
}
exports.Counter = Counter;