Skip to content

Commit

Permalink
refactor: minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
bjarneo committed Jan 28, 2024
1 parent 2b58c43 commit 5985bac
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const fastify = importFastify({

fastify.register(rateLimit, {
prefix: '/api/',
max: 100,
max: 1000, // x requests
timeWindow: 60 * 1000, // 1 minute
});

Expand Down
21 changes: 17 additions & 4 deletions src/server/plugins/rate-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@ import getClientIp from '../helpers/client-ip.js';

const store = new Map();

export default fp(function (fastify, opts, done) {
const defaultOptions = {
prefix: '/',
max: 1000, // x requests
timeWindow: 60 * 1000, // 1 minute
};

// Consider to extract this functionality to a separate plugin,
// and publish it on NPM
// Refactor the code into a class
// and make a redis adapter for it
export default fp(function (fastify, opts = defaultOptions, done) {
fastify.decorate('rateLimit', async (req, res) => {
if (!req.url.startsWith(opts.prefix)) {
done();
Expand All @@ -13,25 +23,28 @@ export default fp(function (fastify, opts, done) {
const key = `${req.method}${req.url}${ip}`;

const currentTime = Date.now();
const resetTime = currentTime + opts.timeWindow;

if (!store.has(key) || currentTime > store.get(key)?.reset) {
store.set(key, {
count: 0,
reset: resetTime,
reset: currentTime + opts.timeWindow,
});
}

const current = store.get(key);
current.count += 1;

const resetTime = Math.floor((current.reset - currentTime) / 1000);

if (current.count > opts.max && currentTime <= current.reset) {
res.header('X-RateLimit-Reset', resetTime);

return res.code(429).send({ message: 'Too many requests, please try again later.' });
}

res.header('X-RateLimit-Limit', opts.max);
res.header('X-RateLimit-Remaining', opts.max - current.count);
res.header('X-RateLimit-Reset', Math.floor((current.reset - currentTime) / 1000));
res.header('X-RateLimit-Reset', resetTime);
});

fastify.addHook('onRequest', fastify.rateLimit);
Expand Down

0 comments on commit 5985bac

Please sign in to comment.