gohiei-koa2-ratelimit
Version:
IP rate-limiting middleware for Koajs 2. Use to limit repeated requests to APIs and/or endpoints such as password reset.
109 lines (93 loc) • 1.9 kB
JavaScript
/**
* RedisStore
*
* RedisStore for koa2-ratelimit
*
* @author Ashok Vishwakarma <akvlko@gmail.com>
*/
/**
* Store
*
* Existing Store class
*/
const Store = require('./Store.js');
/**
* redis
*
* promise-redis module
* https://github.com/maxbrieiev/promise-redis#readme
*/
const redis = require('promise-redis')();
/**
* RedisStore
*
* Class RedisStore
*/
class RedisStore extends Store {
/**
* constructor
* @param {*} config
*
* config is redis config
*/
constructor(config){
super();
this.client = redis.createClient(config);
}
/**
* _hit
* @access private
* @param {*} key
* @param {*} options
* @param {*} weight
*/
async _hit(key, options, weight) {
let [counter, dateEnd] = await this.client.multi().get(key).pttl(key).exec();
if(counter === null) {
counter = weight;
dateEnd = Date.now() + options.interval;
const seconds = Math.ceil(options.interval / 1000);
await this.client.setex(key, seconds, counter);
}else {
if (dateEnd < 0) {
dateEnd = 0;
await this.client.pexpire(key, options.interval);
}
counter = await this.client.incrby(key, weight);
dateEnd = Date.now() + dateEnd;
}
return {
counter,
dateEnd
}
}
/**
* incr
*
* Override incr method from Store class
* @param {*} key
* @param {*} options
* @param {*} weight
*/
async incr(key, options, weight) {
return await this._hit(key, options, weight);
}
/**
* decrement
*
* Override decrement method from Store class
* @param {*} key
* @param {*} options
* @param {*} weight
*/
async decrement(key, options, weight) {
await this.client.decrby(key, weight);
}
/**
* saveAbuse
*
* Override saveAbuse method from Store class
*/
saveAbuse() {}
}
module.exports = RedisStore;