diff --git a/src/RedisStore.js b/src/RedisStore.js index e5a921a..ba3cb3a 100644 --- a/src/RedisStore.js +++ b/src/RedisStore.js @@ -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 @@ -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); }