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
19 changes: 16 additions & 3 deletions src/RedisStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ const redis = require('redis');
*
* Class RedisStore
*/

async function SET_NX_EX (key, seconds, counter, incrIfExists) {
const OK = await this.client.sendCommand([
'SET', key, counter.toString(),
'NX',
'EX', seconds.toString()
])
if (!OK) var counterUpdated = await this.client.incrBy(key, incrIfExists)
return counterUpdated
}

class RedisStore extends Store {
/**
* constructor
Expand All @@ -51,19 +62,21 @@ class RedisStore extends Store {
async _hit(key, options, weight) {

let [counter, dateEnd] = await this.client.multi().get(key).ttl(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.toString(), counter.toString());
const counterUpdated = await SET_NX_EX.call(this, key, seconds, counter, weight)
if (counterUpdated) { counter = counterUpdated }
} else if (dateEnd === -2 || dateEnd === -1) {
counter = counter + weight;
dateEnd = Date.now() + options.interval;

const seconds = Math.ceil(options.interval / 1000);
await this.client.setEx(key, seconds.toString(), counter.toString());
const counterUpdated = await SET_NX_EX.call(this, key, seconds, counter, weight)
if (counterUpdated) { counter = counterUpdated }
} else {
counter = await this.client.incrBy(key, weight);
}
Expand Down