Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix redis key ttl avoid non-ttl situation #15

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
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 <[email protected]>
*/

/**
* 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;
gohiei marked this conversation as resolved.
Show resolved Hide 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