Skip to content

Commit

Permalink
feat: Added default rate limit middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Adil committed Sep 21, 2024
1 parent 6692dcd commit 06cbcf2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/api/middlewares/default-rate-limit.ts
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)
}
}
1 change: 1 addition & 0 deletions src/index.ts
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'

0 comments on commit 06cbcf2

Please sign in to comment.