diff --git a/.gitignore b/.gitignore index 3c3629e..cd98105 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules +.idea/ \ No newline at end of file diff --git a/index.js b/index.js index ab8675b..7b6df8f 100644 --- a/index.js +++ b/index.js @@ -1,19 +1,28 @@ module.exports = function (app, db) { + var dbError = false + db.on('error', function (err) { + dbError = true + }) + db.on('connect', function () { + dbError = false + }) return function (opts) { var middleware = function (req, res, next) { + if(dbError === true) return next() if (opts.whitelist && opts.whitelist(req)) return next() opts.lookup = Array.isArray(opts.lookup) ? opts.lookup : [opts.lookup] opts.onRateLimited = typeof opts.onRateLimited === 'function' ? opts.onRateLimited : function (req, res, next) { res.status(429).send('Rate limit exceeded') } var lookups = opts.lookup.map(function (item) { - return item + ':' + item.split('.').reduce(function (prev, cur) { + return item.split('.').reduce(function (prev, cur) { return prev[cur] }, req) }).join(':') var path = opts.path || req.path var method = (opts.method || req.method).toLowerCase() - var key = 'ratelimit:' + path + ':' + method + ':' + lookups + var prefix = opts.prefix_redis_key || 'ratelimit:' + path + ':' + method; + var key = prefix + ':' + lookups db.get(key, function (err, limit) { if (err && opts.ignoreErrors) return next() var now = Date.now()