-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Added default rate limit middleware
- Loading branch information
Adil
committed
Sep 21, 2024
1 parent
6692dcd
commit 06cbcf2
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { type MedusaRequest, type MedusaResponse } from '@medusajs/medusa' | ||
import type { NextFunction } from 'express' | ||
import type RateLimitService from '../../services/rate-limit' | ||
|
||
/** | ||
* A simple rate limiter middleware based on the RateLimitService | ||
* @param limit {number} - Number of requests allowed per window | ||
* @param window {number} - Number of seconds to wait before allowing requests again | ||
* @returns | ||
*/ | ||
export default async function defaultRateLimit( | ||
req: MedusaRequest, | ||
res: MedusaResponse, | ||
next: NextFunction, | ||
) { | ||
try { | ||
const rateLimitService = req.scope.resolve<RateLimitService>('rateLimitService') | ||
|
||
const key = req.ip | ||
const rateLimitKey = `rate_limit:${key}` | ||
const allowed = await rateLimitService.limit(rateLimitKey) | ||
|
||
if (!allowed) { | ||
const retryAfter = await rateLimitService.ttl(rateLimitKey) | ||
res.set('Retry-After', String(retryAfter)) | ||
res | ||
.status(429) | ||
.json({ error: 'Too many requests, please try again later.' }) | ||
return | ||
} | ||
|
||
const remaining = await rateLimitService.getRemainingAttempts(rateLimitKey) | ||
|
||
res.set('X-RateLimit-Limit', String(rateLimitService.getOptions().limit)) | ||
res.set('X-RateLimit-Remaining', String(remaining)) | ||
|
||
next() | ||
} catch (error) { | ||
next(error) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export { default as RateLimitService } from './services/rate-limit' | ||
export { default as rateLimitRoutes } from './api/middlewares/default-rate-limit' | ||
export { PluginOptions } from './types/options' |