UNPKG

@routup/rate-limit-redis

Version:

Red adapter for the routup rate-limit plugin.

81 lines (78 loc) 2.21 kB
import { useClient, createClient } from 'redis-extension'; import { calculateNextResetTime } from '@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 = 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 = useClient(); } else { this.client = createClient({ connectionString }); } } } export { RedisStore, RedisStore as default }; //# sourceMappingURL=index.mjs.map