Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow the message option to be a function #311

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,30 @@ const limiter = rateLimit({
The response body to send back when a client is rate limited.

May be a `string`, JSON object, or any other value that Express's
[response.send](https://expressjs.com/en/4x/api.html#response.send) method
supports.
[`response.send`](https://expressjs.com/en/4x/api.html#res.send) method
supports. It can also be a (sync/async) function that accepts the Express
request and response objects and then returns a `string`, JSON object or any
other value the Express `response.send` function accepts.

colderry marked this conversation as resolved.
Show resolved Hide resolved
Defaults to `'Too many requests, please try again later.'`

An example of using a function:

```ts
const isPremium = async (user) => {
// ...
}

const limiter = rateLimit({
// ...
message: async (request, response) => {
if (await isPremium(request.user))
return 'You can only make 10 requests every hour.'
else return 'You can only make 5 requests every hour.'
},
})
```

### `statusCode`

> `number`
Expand Down Expand Up @@ -348,7 +367,8 @@ const limiter = rateLimit({
Express request handler that sends back a response when a client is
rate-limited.

By default, sends back the `statusCode` and `message` set via the options:
By default, sends back the `statusCode` and `message` set via the `options`,
similar to this:

```ts
const limiter = rateLimit({
Expand Down
24 changes: 19 additions & 5 deletions source/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ const promisifyStore = (passedStore: LegacyStore | Store): Store => {
interface Configuration {
windowMs: number
max: number | ValueDeterminingMiddleware<number>
message: any
message: any | ValueDeterminingMiddleware<any>
statusCode: number
legacyHeaders: boolean
standardHeaders: boolean
Expand Down Expand Up @@ -144,13 +144,27 @@ const parseOptions = (passedOptions: Partial<Options>): Configuration => {

return request.ip
},
handler(
_request: Request,
async handler(
request: Request,
response: Response,
_next: NextFunction,
_optionsUsed: Options,
): void {
response.status(config.statusCode).send(config.message)
): Promise<void> {
// Set the response status code
response.status(config.statusCode)
// Call the `message` if it is a function.
const message: unknown =
typeof config.message === 'function'
? await (config.message as ValueDeterminingMiddleware<any>)(
request,
response,
)
: config.message

// Send the response if writable.
if (!response.writableEnded) {
response.send(message ?? 'Too many requests, please try again later.')
}
},
onLimitReached(
_request: Request,
Expand Down
2 changes: 1 addition & 1 deletion source/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export interface Options {
*
* Defaults to `'Too many requests, please try again later.'`
*/
readonly message: any
readonly message: any | ValueDeterminingMiddleware<any>

/**
* The HTTP status code to send back when a client is rate limited.
Expand Down
28 changes: 25 additions & 3 deletions test/library/middleware-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,30 @@ describe('middleware test', () => {
await request(app).get('/').expect(429, message)
})

it('should allow message to be a function', async () => {
const app = createServer(
rateLimit({
message: () => 'Too many requests.',
max: 1,
}),
)

await request(app).get('/').expect(200, 'Hi there!')
await request(app).get('/').expect(429, 'Too many requests.')
})

it('should allow message to be a function that returns a promise', async () => {
const app = createServer(
rateLimit({
message: async () => 'Too many requests.',
max: 1,
}),
)

await request(app).get('/').expect(200, 'Hi there!')
await request(app).get('/').expect(429, 'Too many requests.')
})

it('should use a custom handler when specified', async () => {
const app = createServer(
rateLimit({
Expand Down Expand Up @@ -303,9 +327,7 @@ describe('middleware test', () => {
it('should allow custom skip function that returns a promise', async () => {
const limiter = rateLimit({
max: 2,
async skip() {
return true
},
skip: async () => true,
})

const app = createServer(limiter)
Expand Down