refactoring user_limits_api

This commit is contained in:
Simon Martín 2018-03-02 16:07:42 +01:00
parent bf267e9c95
commit 4dd404771e

View File

@ -93,9 +93,9 @@ UserLimitsApi.prototype.preprareRateLimit = function () {
if (this.options.limits.rateLimitsEnabled) {
this.metadataBackend.redisCmd(
RATE_LIMIT_REDIS_DB,
'SCRIPT',
['LOAD', getRateLimitLuaScript()],
RATE_LIMIT_REDIS_DB,
'SCRIPT',
['LOAD', getRateLimitLuaScript()],
function (err, sha) {
if (!err && sha) {
self.rateLimits.sha = sha;
@ -117,21 +117,20 @@ UserLimitsApi.prototype.getRateLimit = function (user, endpointGroup, callback)
];
this.metadataBackend.redisCmd(
RATE_LIMIT_REDIS_DB,
this.rateLimits.redisCommand,
redisParams,
RATE_LIMIT_REDIS_DB,
this.rateLimits.redisCommand,
redisParams,
function (err, rateLimits) {
if (err && err.name === 'ReplyError' && err.message === 'NOSCRIPT No matching script. Please use EVAL.') {
self.rateLimits.redisCommand = 'EVAL';
return self.getRateLimit(user, endpointGroup, callback);
if (err) {
if (err.name === 'ReplyError' && err.message === 'NOSCRIPT No matching script. Please use EVAL.') {
self.rateLimits.redisCommand = 'EVAL';
return self.getRateLimit(user, endpointGroup, callback);
} else {
callback(err);
}
}
let rateLimit;
if (!err) {
rateLimit = getLowerRateLimit(rateLimits);
}
callback(err, rateLimit);
callback(null, getLowerRateLimit(rateLimits));
}
);
};
@ -188,16 +187,15 @@ function getRateLimitLuaScript() {
*/
function getLowerRateLimit(rateLimits) {
/*jshint maxcomplexity:10 */
if (!rateLimits || !Array.isArray(rateLimits) || !rateLimits.length) {
if (!Array.isArray(rateLimits) || !rateLimits.length) {
return;
}
let minIndex = 0;
let minIndex;
let minRemainingValue;
let currentIndex = 0;
for (let rateLimit of rateLimits) {
for (let currentIndex = 0; currentIndex < rateLimits.length; currentIndex++) {
const rateLimit = rateLimits[currentIndex];
if (!validateRatelimit(rateLimit)) {
currentIndex++;
continue;
}
@ -212,11 +210,9 @@ function getLowerRateLimit(rateLimits) {
minIndex = currentIndex;
minRemainingValue = remaining;
}
currentIndex++;
}
if (validateRatelimit(rateLimits[minIndex])) {
if (rateLimits[minIndex]) {
return rateLimits[minIndex];
} else {
return;