diff --git a/src/middleware/rateLimiter.ts b/src/middleware/rateLimiter.ts new file mode 100644 index 00000000..7a91e82b --- /dev/null +++ b/src/middleware/rateLimiter.ts @@ -0,0 +1,10 @@ +import rateLimit from 'express-rate-limit'; +import { Express } from '../types'; + +export const rateLimiter: Express.MiddleWare = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes in milliseconds + max: 20, + message: 'Too many requests, please try again later', + standardHeaders: true, + legacyHeaders: false, +}); diff --git a/src/routers/router.ts b/src/routers/router.ts index c67bd8f9..8bb832b7 100644 --- a/src/routers/router.ts +++ b/src/routers/router.ts @@ -1,5 +1,4 @@ import express from 'express'; -import rateLimit from 'express-rate-limit'; import { Express } from '../types'; import { getWords, getWord } from '../controllers/words'; import { getExamples, getExample } from '../controllers/examples'; @@ -11,25 +10,18 @@ import validateApiKey from '../middleware/validateApiKey'; import validateAdminApiKey from '../middleware/validateAdminApiKey'; import attachRedisClient from '../middleware/attachRedisClient'; import analytics from '../middleware/analytics'; +import { rateLimiter } from '../middleware/rateLimiter'; const router = express.Router(); -const FIFTEEN_MINUTES = 15 * 60 * 1000; -const REQUESTS_PER_MS = 20; -const createDeveloperLimiter: Express.MiddleWare = rateLimit({ - windowMs: FIFTEEN_MINUTES, - max: REQUESTS_PER_MS, -}); - -// Google Analytics -router.use(analytics); +router.use(analytics, rateLimiter); router.get('/words', validateApiKey, attachRedisClient, getWords); router.get('/words/:id', validateApiKey, validId, attachRedisClient, getWord); router.get('/examples', validateApiKey, attachRedisClient, getExamples); router.get('/examples/:id', validateApiKey, validId, attachRedisClient, getExample); -router.post('/developers', createDeveloperLimiter, validateDeveloperBody, postDeveloper); +router.post('/developers', validateDeveloperBody, postDeveloper); router.get('/stats', validateAdminApiKey, attachRedisClient, getStats); diff --git a/src/routers/routerV2.ts b/src/routers/routerV2.ts index 80980a17..d5667347 100644 --- a/src/routers/routerV2.ts +++ b/src/routers/routerV2.ts @@ -5,9 +5,12 @@ import validId from '../middleware/validId'; import validateApiKey from '../middleware/validateApiKey'; import analytics from '../middleware/analytics'; import attachRedisClient from '../middleware/attachRedisClient'; +import { rateLimiter } from '../middleware/rateLimiter'; const routerV2 = express.Router(); +routerV2.use(rateLimiter); + routerV2.get('/words', analytics, validateApiKey, attachRedisClient, getWords); routerV2.get('/words/:id', analytics, validateApiKey, validId, attachRedisClient, getWord); routerV2.get('/examples', analytics, validateApiKey, attachRedisClient, getExamples);