UNPKG

@routup/rate-limit-redis

Version:

Red adapter for the routup rate-limit plugin.

87 lines (82 loc) 2.38 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var redisExtension = require('redis-extension'); var rateLimit = require('@routup/rate-limit'); class RedisStore { /** * Method that initializes the store. * * @param options {Options} - The options used to setup the middleware. */ init(options) { this.options = options; } /** * Method to increment a client's hit counter. * * @param key {string} - The identifier for a client. * * @returns {IncrementResponse} - The number of hits and reset time for that client. * * @public */ async increment(key) { key = this.buildKey(key); const entry = await this.client.get(key); let totalHits; if (entry) { totalHits = parseInt(entry, 10) + 1; } else { totalHits = 1; } this.client.set(key, totalHits, 'PX', this.options.windowMs); const resetTime = rateLimit.calculateNextResetTime(this.options.windowMs); return { totalHits, resetTime }; } /** * Method to decrement a client's hit counter. * * @param key {string} - The identifier for a client. * * @public */ async decrement(key) { key = this.buildKey(key); const entry = await this.client.get(key); if (entry) { const totalHits = parseInt(entry, 10) - 1; this.client.set(key, totalHits, 'PX', this.options.windowMs); } } /** * Method to reset a client's hit counter. * * @param key {string} - The identifier for a client. * * @public */ async reset(key) { key = this.buildKey(key); this.client.del(key); } /** * Method to build redis key. * * @param key * @protected */ buildKey(key) { return `rate-limit:${key}`; } constructor(connectionString){ if (typeof connectionString === 'undefined') { this.client = redisExtension.useClient(); } else { this.client = redisExtension.createClient({ connectionString }); } } } exports.RedisStore = RedisStore; exports.default = RedisStore; module.exports = Object.assign(exports.default, exports); //# sourceMappingURL=index.cjs.map