Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 27 additions & 21 deletions src/RedisStore.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
/**
* 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
*
* @param {*} config
*
* config is redis config
*/
constructor(config){
Expand All @@ -41,22 +41,28 @@ class RedisStore extends Store {
/**
* _hit
* @access private
* @param {*} key
* @param {*} options
* @param {*} weight
* @param {*} key
* @param {*} options
* @param {*} weight
*/
async _hit(key, options, weight) {

let [counter, dateEnd] = await this.client.multi().get(key).ttl(key).exec();
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;
}

counter = await this.client.incrby(key, weight);

dateEnd = Date.now() + dateEnd;
Comment thread
gohiei marked this conversation as resolved.
}

return {
Expand All @@ -67,31 +73,31 @@ class RedisStore extends Store {

/**
* incr
*
*
* Override incr method from Store class
* @param {*} key
* @param {*} options
* @param {*} weight
* @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
* @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() {}
Expand Down