@mvp-rockets/namma-ratelimit
Version:
A package to handle ratelimit in node apis
40 lines (37 loc) • 1.29 kB
JavaScript
const rateLimit = require('express-rate-limit')
const { createClient } = require('redis');
const RedisStore = require("rate-limit-redis");
const { logError, ApiError } = require('@mvp-rockets/namma-lib/utilities');
const { HTTP_CONSTANT } = require("@mvp-rockets/namma-lib")
const config = {};
let client;
const reload = () => {
client = createClient(config.configurations);
client.connect().then(() => {
console.log("Successfully connected to redis server")
});
client.on('error', err => {
console.log('Error ' + err);
});
};
const initialize = (configurations) => {
config.configurations = configurations;
reload();
};
const requestsPerMin = (times) => rateLimit({
windowMs: 60 * 1000, // 1 min
max: times,
message: 'Too many accounts created from this IP, please try again after an hour',
standardHeaders: true,
legacyHeaders: false,
store: new RedisStore({
sendCommand: (...args) => {
return client.sendCommand(args)
},
}),
handler: (request, response, next, options) => {
logError("Ip blocked exceeded the rate limit", options)
next(new ApiError(options, options.message, HTTP_CONSTANT.TOO_MANY_REQUESTS))
}
})
module.exports = { requestsPerMin, initialize };