express-rate-limit-ioredis-store
Version:
A redis store implementation to be used alongside ioredis for the express-rate-limit middleware
48 lines • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class ExpressRateLimitIORedisStore {
constructor({ globalPrefix, client }) {
this.client = client;
this.globalPrefix = globalPrefix !== null && globalPrefix !== void 0 ? globalPrefix : 'express-rate-limit-store-';
this.windowMs = 0;
}
init(options) {
this.windowMs = options.windowMs;
}
async increment(key) {
const redisKey = this.getFullKey(key);
const totalHits = await this.client.incr(redisKey);
const insertionTime = await this.getInsertionTime(redisKey, totalHits);
const expiryTime = insertionTime + this.windowMs;
await this.client.pexpireat(redisKey, expiryTime);
return {
totalHits,
resetTime: new Date(expiryTime),
};
}
async decrement(key) {
const redisKey = this.getFullKey(key);
if (await this.client.get(redisKey)) {
await this.client.decr(redisKey);
}
}
async resetKey(key) {
await this.client.del(this.getFullKey(key));
}
getFullKey(key) {
return this.globalPrefix + key;
}
async getInsertionTime(key, value) {
const isKeyInsertion = value === 1;
if (isKeyInsertion) {
const now = new Date().getTime();
await this.client.set(key + '-create-time', now);
await this.client.pexpire(key + '-create-time', this.windowMs);
return now;
}
const createTime = await this.client.get(key + '-create-time');
return parseInt(createTime);
}
}
exports.default = ExpressRateLimitIORedisStore;
//# sourceMappingURL=index.js.map