Skip to content

Instantly share code, notes, and snippets.

@maapteh
Last active December 11, 2019 04:11
Show Gist options
  • Save maapteh/e79e5dc2818ba16d262c1a3c7233249c to your computer and use it in GitHub Desktop.
Save maapteh/e79e5dc2818ba16d262c1a3c7233249c to your computer and use it in GitHub Desktop.
rate limiter example
function (limit) {
const RateLimiter = require('limiter').RateLimiter;
const isUserAnonymous = require('./helper/is-anonymous');
const limiter = new RateLimiter(limit, 'second', true);
return (req, res, next) => {
const isAnonymous = isUserAnonymous(req);
if (isAnonymous) {
next();
}
if (limiter.tryRemoveTokens(1)) {
next();
} else {
res.locals.ratelimited = true;
next();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment