Skip to content

Commit

Permalink
feat: added rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
niloysikdar committed Jan 26, 2022
1 parent 1b6eb69 commit 245c2a6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"dotenv": "^14.3.2",
"fastify": "^3.27.0",
"fastify-cors": "^6.0.2",
"fastify-rate-limit": "^5.7.0",
"mongodb": "^4.3.1"
},
"devDependencies": {
Expand Down
13 changes: 12 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ const MONGODB_URL = process.env.MONGODB_URL;
const PORT = process.env.PORT || 5000;

fastify.register(require("fastify-cors"), {});
fastify.register(require("fastify-rate-limit"), {
global: true,
max: 3,
timeWindow: 1000 * 60,
errorResponseBuilder: function (req, context) {
return {
code: 429,
error: "Too Many Requests",
message: `I only allow ${context.max} requests per ${context.after} to this API. Try again after ${context.ttl} ms !`,
};
},
});

const client = new MongoClient(MONGODB_URL);

Expand All @@ -34,7 +46,6 @@ fastify.get("/", async (req, res) => {
});

// Connect the DB and Run the server!

client
.connect()
.then(() => startServer())
Expand Down
9 changes: 9 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,15 @@ fastify-plugin@^3.0.0:
resolved "https://registry.yarnpkg.com/fastify-plugin/-/fastify-plugin-3.0.1.tgz#79e84c29f401020f38b524f59f2402103fd21ed2"
integrity sha512-qKcDXmuZadJqdTm6vlCqioEbyewF60b/0LOFCcYN1B6BIZGlYJumWWOYs70SFYLDAH4YqdE1cxH/RKMG7rFxgA==

fastify-rate-limit@^5.7.0:
version "5.7.0"
resolved "https://registry.yarnpkg.com/fastify-rate-limit/-/fastify-rate-limit-5.7.0.tgz#50a4ec3183e7b357c629e99d10260f65a0950bb3"
integrity sha512-9pfnVpz6rUy7VGqBVN9blIT7LgmETiK7hRA0Pu8eHJFq8qq8FBPvrQYXxGXb2nt63laD6ZuvT1O7TxucZI1HIA==
dependencies:
fastify-plugin "^3.0.0"
ms "^2.1.1"
tiny-lru "^7.0.0"

fastify-warning@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/fastify-warning/-/fastify-warning-0.2.0.tgz#e717776026a4493dc9a2befa44db6d17f618008f"
Expand Down

0 comments on commit 245c2a6

Please sign in to comment.