diff --git a/src/RedisStore.js b/src/RedisStore.js index 964a2a7..f5b33be 100644 --- a/src/RedisStore.js +++ b/src/RedisStore.js @@ -1,21 +1,21 @@ /** * RedisStore - * + * * RedisStore for koa2-ratelimit - * + * * @author Ashok Vishwakarma */ /** * Store - * + * * Existing Store class */ const Store = require('./Store.js'); /** * redis - * + * * promise-redis module * https://github.com/maxbrieiev/promise-redis#readme */ @@ -23,14 +23,14 @@ const redis = require('promise-redis')(); /** * RedisStore - * + * * Class RedisStore */ class RedisStore extends Store { /** * constructor - * @param {*} config - * + * @param {*} config + * * config is redis config */ constructor(config){ @@ -41,14 +41,14 @@ 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; @@ -56,7 +56,13 @@ class RedisStore extends Store { 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; } return { @@ -67,11 +73,11 @@ 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); @@ -79,11 +85,11 @@ class RedisStore extends Store { /** * 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); @@ -91,7 +97,7 @@ class RedisStore extends Store { /** * saveAbuse - * + * * Override saveAbuse method from Store class */ saveAbuse() {}