@nestjs/throttler 4.2.1 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +244 -166
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/throttler-module-options.interface.d.ts +12 -4
- package/dist/throttler-storage.interface.d.ts +0 -2
- package/dist/throttler-storage.interface.js.map +1 -1
- package/dist/throttler.decorator.d.ts +8 -2
- package/dist/throttler.decorator.js +14 -12
- package/dist/throttler.decorator.js.map +1 -1
- package/dist/throttler.guard.d.ts +12 -5
- package/dist/throttler.guard.interface.d.ts +7 -0
- package/dist/throttler.guard.interface.js +3 -0
- package/dist/throttler.guard.interface.js.map +1 -0
- package/dist/throttler.guard.js +77 -30
- package/dist/throttler.guard.js.map +1 -1
- package/dist/throttler.module.js +3 -2
- package/dist/throttler.module.js.map +1 -1
- package/dist/throttler.providers.d.ts +2 -1
- package/dist/throttler.providers.js +3 -1
- package/dist/throttler.providers.js.map +1 -1
- package/dist/throttler.service.js +3 -2
- package/dist/throttler.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/utilities.d.ts +5 -0
- package/dist/utilities.js +14 -0
- package/dist/utilities.js.map +1 -0
- package/package.json +39 -38
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# The MIT License
|
|
2
2
|
|
|
3
|
-
Copyright 2019-
|
|
3
|
+
Copyright 2019-2023 Jay McDoniel, contributors
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
6
|
|
package/README.md
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
<p align="center">
|
|
2
2
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
|
3
3
|
</p>
|
|
4
|
-
|
|
5
4
|
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
|
|
6
5
|
[travis-url]: https://travis-ci.org/nestjs/nest
|
|
7
6
|
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
|
|
@@ -12,16 +11,12 @@
|
|
|
12
11
|
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
|
13
12
|
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
|
14
13
|
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
|
|
15
|
-
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
|
|
16
|
-
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
|
|
17
14
|
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
|
|
18
15
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
|
19
16
|
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
|
20
17
|
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
|
21
18
|
<a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
|
|
22
19
|
</p>
|
|
23
|
-
<!--[](https://opencollective.com/nest#backer)
|
|
24
|
-
[](https://opencollective.com/nest#sponsor)-->
|
|
25
20
|
|
|
26
21
|
## Description
|
|
27
22
|
|
|
@@ -43,6 +38,8 @@ $ npm i --save @nestjs/throttler
|
|
|
43
38
|
|
|
44
39
|
For NestJS v10, please use version 4.1.0 or above
|
|
45
40
|
|
|
41
|
+
<div id="toc"></div>
|
|
42
|
+
|
|
46
43
|
## Table of Contents
|
|
47
44
|
|
|
48
45
|
- [Description](#description)
|
|
@@ -50,216 +47,155 @@ For NestJS v10, please use version 4.1.0 or above
|
|
|
50
47
|
- [Table of Contents](#table-of-contents)
|
|
51
48
|
- [Usage](#usage)
|
|
52
49
|
- [ThrottlerModule](#throttlermodule)
|
|
53
|
-
- [
|
|
54
|
-
|
|
55
|
-
- [@SkipThrottle()](#skipthrottle)
|
|
56
|
-
- [Ignoring specific user agents](#ignoring-specific-user-agents)
|
|
57
|
-
- [ThrottlerStorage](#throttlerstorage)
|
|
50
|
+
- [Customization](#customization)
|
|
51
|
+
- [ThrottlerStorage](#storages)
|
|
58
52
|
- [Proxies](#proxies)
|
|
59
|
-
- [Working with Websockets](#
|
|
60
|
-
- [Working with GraphQL](#
|
|
53
|
+
- [Working with Websockets](#websockets)
|
|
54
|
+
- [Working with GraphQL](#graphql)
|
|
61
55
|
- [Community Storage Providers](#community-storage-providers)
|
|
62
56
|
|
|
63
57
|
## Usage
|
|
64
58
|
|
|
65
59
|
### ThrottlerModule
|
|
66
60
|
|
|
67
|
-
|
|
68
|
-
in a synchronous or asynchronous manner. All the needs to be passed is the
|
|
69
|
-
`ttl`, the time to live in seconds for the request tracker, and the `limit`, or
|
|
70
|
-
how many times an endpoint can be hit before returning a 429.
|
|
71
|
-
|
|
72
|
-
```ts
|
|
73
|
-
import { APP_GUARD } from '@nestjs/core';
|
|
74
|
-
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
|
61
|
+
Once the installation is complete, the `ThrottlerModule` can be configured as any other Nest package with `forRoot` or `forRootAsync` methods.
|
|
75
62
|
|
|
63
|
+
```typescript
|
|
64
|
+
@@filename(app.module)
|
|
76
65
|
@Module({
|
|
77
66
|
imports: [
|
|
78
|
-
ThrottlerModule.forRoot({
|
|
79
|
-
ttl:
|
|
67
|
+
ThrottlerModule.forRoot([{
|
|
68
|
+
ttl: 60000,
|
|
80
69
|
limit: 10,
|
|
81
|
-
}),
|
|
82
|
-
],
|
|
83
|
-
providers: [
|
|
84
|
-
{
|
|
85
|
-
provide: APP_GUARD,
|
|
86
|
-
useClass: ThrottlerGuard,
|
|
87
|
-
},
|
|
70
|
+
}]),
|
|
88
71
|
],
|
|
89
72
|
})
|
|
90
73
|
export class AppModule {}
|
|
91
74
|
```
|
|
92
75
|
|
|
93
|
-
The above
|
|
76
|
+
The above will set the global options for the `ttl`, the time to live in milliseconds, and the `limit`, the maximum number of requests within the ttl, for the routes of your application that are guarded.
|
|
94
77
|
|
|
95
|
-
|
|
96
|
-
@Module({
|
|
97
|
-
imports: [
|
|
98
|
-
ThrottlerModule.forRootAsync({
|
|
99
|
-
imports: [ConfigModule],
|
|
100
|
-
inject: [ConfigService],
|
|
101
|
-
useFactory: (config: ConfigService) => ({
|
|
102
|
-
ttl: config.get('THROTTLE_TTL'),
|
|
103
|
-
limit: config.get('THROTTLE_LIMIT'),
|
|
104
|
-
}),
|
|
105
|
-
}),
|
|
106
|
-
],
|
|
107
|
-
providers: [
|
|
108
|
-
{
|
|
109
|
-
provide: APP_GUARD,
|
|
110
|
-
useClass: ThrottlerGuard,
|
|
111
|
-
},
|
|
112
|
-
],
|
|
113
|
-
})
|
|
114
|
-
export class AppModule {}
|
|
115
|
-
```
|
|
78
|
+
Once the module has been imported, you can then choose how you would like to bind the `ThrottlerGuard`. Any kind of binding as mentioned in the [guards](https://docs.nestjs.com/guards) section is fine. If you wanted to bind the guard globally, for example, you could do so by adding this provider to any module:
|
|
116
79
|
|
|
117
|
-
|
|
80
|
+
```typescript
|
|
81
|
+
{
|
|
82
|
+
provide: APP_GUARD,
|
|
83
|
+
useClass: ThrottlerGuard
|
|
84
|
+
}
|
|
85
|
+
```
|
|
118
86
|
|
|
119
|
-
|
|
120
|
-
then all the incoming requests will be throttled by default. This can also be
|
|
121
|
-
omitted in favor of `@UseGuards(ThrottlerGuard)`. The global guard check can be
|
|
122
|
-
skipped using the `@SkipThrottle()` decorator mentioned later.
|
|
87
|
+
#### Multiple Throttler Definitions
|
|
123
88
|
|
|
124
|
-
|
|
89
|
+
There may come upon times where you want to set up multiple throttling definitions, like no more than 3 calls in a second, 20 calls in 10 seconds, and 100 calls in a minute. To do so, you can set up your definitions in the array with named options, that can later be referenced in the `@SkipThrottle()` and `@Throttle()` decorators to change the options again.
|
|
125
90
|
|
|
126
|
-
```
|
|
127
|
-
|
|
91
|
+
```typescript
|
|
92
|
+
@@filename(app.module)
|
|
128
93
|
@Module({
|
|
129
94
|
imports: [
|
|
130
|
-
ThrottlerModule.forRoot(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
95
|
+
ThrottlerModule.forRoot([
|
|
96
|
+
{
|
|
97
|
+
name: 'short',
|
|
98
|
+
ttl: 1000,
|
|
99
|
+
limit: 3,
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: 'medium',
|
|
103
|
+
ttl: 10000,
|
|
104
|
+
limit: 20
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
name: 'long',
|
|
108
|
+
ttl: 60000,
|
|
109
|
+
limit: 100
|
|
110
|
+
}
|
|
111
|
+
]),
|
|
134
112
|
],
|
|
135
113
|
})
|
|
136
114
|
export class AppModule {}
|
|
137
|
-
|
|
138
|
-
// app.controller.ts
|
|
139
|
-
@Controller()
|
|
140
|
-
export class AppController {
|
|
141
|
-
@UseGuards(ThrottlerGuard)
|
|
142
|
-
@Throttle(5, 30)
|
|
143
|
-
normal() {}
|
|
144
|
-
}
|
|
145
115
|
```
|
|
146
116
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
#### @Throttle()
|
|
117
|
+
#### Customization
|
|
150
118
|
|
|
151
|
-
|
|
152
|
-
@Throttle(limit: number = 30, ttl: number = 60)
|
|
153
|
-
```
|
|
119
|
+
There may be a time where you want to bind the guard to a controller or globally, but want to disable rate limiting for one or more of your endpoints. For that, you can use the `@SkipThrottle()` decorator, to negate the throttler for an entire class or a single route. The `@SkipThrottle()` decorator can also take in an object of string keys with boolean values for if there is a case where you want to exclude _most_ of a controller, but not every route, and configure it per throttler set if you have more than one. If you do not pass an object, the default is to use `{{ '{' }} default: true {{ '}' }}`
|
|
154
120
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
#### @SkipThrottle()
|
|
160
|
-
|
|
161
|
-
```ts
|
|
162
|
-
@SkipThrottle(skip = true)
|
|
121
|
+
```typescript
|
|
122
|
+
@SkipThrottle()
|
|
123
|
+
@Controller('users')
|
|
124
|
+
export class UsersController {}
|
|
163
125
|
```
|
|
164
126
|
|
|
165
|
-
This decorator can be used to skip a route or a class
|
|
166
|
-
skipping of a route in a class that is skipped.
|
|
127
|
+
This `@SkipThrottle()` decorator can be used to skip a route or a class or to negate the skipping of a route in a class that is skipped.
|
|
167
128
|
|
|
168
|
-
```
|
|
129
|
+
```typescript
|
|
169
130
|
@SkipThrottle()
|
|
170
|
-
@Controller()
|
|
171
|
-
export class
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
131
|
+
@Controller('users')
|
|
132
|
+
export class UsersController {
|
|
133
|
+
// Rate limiting is applied to this route.
|
|
134
|
+
@SkipThrottle({ default: false })
|
|
135
|
+
dontSkip() {
|
|
136
|
+
return 'List users work with Rate limiting.';
|
|
137
|
+
}
|
|
138
|
+
// This route will skip rate limiting.
|
|
139
|
+
doSkip() {
|
|
140
|
+
return 'List users work without Rate limiting.';
|
|
141
|
+
}
|
|
176
142
|
}
|
|
177
143
|
```
|
|
178
144
|
|
|
179
|
-
|
|
180
|
-
while `doSkip` would not be limited in any way.
|
|
181
|
-
|
|
182
|
-
### Ignoring specific user agents
|
|
183
|
-
|
|
184
|
-
You can use the `ignoreUserAgents` key to ignore specific user agents.
|
|
185
|
-
|
|
186
|
-
```ts
|
|
187
|
-
@Module({
|
|
188
|
-
imports: [
|
|
189
|
-
ThrottlerModule.forRoot({
|
|
190
|
-
ttl: 60,
|
|
191
|
-
limit: 10,
|
|
192
|
-
ignoreUserAgents: [
|
|
193
|
-
// Don't throttle request that have 'googlebot' defined in them.
|
|
194
|
-
// Example user agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
|
|
195
|
-
/googlebot/gi,
|
|
196
|
-
|
|
197
|
-
// Don't throttle request that have 'bingbot' defined in them.
|
|
198
|
-
// Example user agent: Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)
|
|
199
|
-
new RegExp('bingbot', 'gi'),
|
|
200
|
-
],
|
|
201
|
-
}),
|
|
202
|
-
],
|
|
203
|
-
})
|
|
204
|
-
export class AppModule {}
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
### ThrottlerStorage
|
|
208
|
-
|
|
209
|
-
Interface to define the methods to handle the details when it comes to keeping track of the requests.
|
|
210
|
-
|
|
211
|
-
Currently the key is seen as an `MD5` hash of the `IP` the `ClassName` and the
|
|
212
|
-
`MethodName`, to ensure that no unsafe characters are used and to ensure that
|
|
213
|
-
the package works for contexts that don't have explicit routes (like Websockets
|
|
214
|
-
and GraphQL).
|
|
145
|
+
There is also the `@Throttle()` decorator which can be used to override the `limit` and `ttl` set in the global module, to give tighter or looser security options. This decorator can be used on a class or a function as well. With version 5 and onwards, the decorator takes in an object with the string relating to the name of the throttler set, and an object with the limit and ttl keys and integer values, similar to the options passed to the root module. If you do not have a name set in your original options, use the string `default` You have to configure it like this:
|
|
215
146
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
147
|
+
```typescript
|
|
148
|
+
// Override default configuration for Rate limiting and duration.
|
|
149
|
+
@Throttle({ default: { limit: 3, ttl: 60000 } })
|
|
150
|
+
@Get()
|
|
151
|
+
findAll() {
|
|
152
|
+
return "List users works with custom rate limiting.";
|
|
222
153
|
}
|
|
223
154
|
```
|
|
224
155
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
### Proxies
|
|
156
|
+
#### Proxies
|
|
228
157
|
|
|
229
|
-
If
|
|
158
|
+
If your application runs behind a proxy server, check the specific HTTP adapter options ([express](http://expressjs.com/en/guide/behind-proxies.html) and [fastify](https://www.fastify.io/docs/latest/Reference/Server/#trustproxy)) for the `trust proxy` option and enable it. Doing so will allow you to get the original IP address from the `X-Forwarded-For` header, and you can override the `getTracker()` method to pull the value from the header rather than from `req.ip`. The following example works with both express and fastify:
|
|
230
159
|
|
|
231
|
-
```
|
|
160
|
+
```typescript
|
|
232
161
|
// throttler-behind-proxy.guard.ts
|
|
233
162
|
import { ThrottlerGuard } from '@nestjs/throttler';
|
|
234
163
|
import { Injectable } from '@nestjs/common';
|
|
235
164
|
|
|
236
165
|
@Injectable()
|
|
237
166
|
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
|
|
238
|
-
protected getTracker(req: Record<string, any>): string {
|
|
239
|
-
|
|
167
|
+
protected getTracker(req: Record<string, any>): Promise<string> {
|
|
168
|
+
return new Promise<string>((resolve, reject) => {
|
|
169
|
+
const tracker = req.ips.length > 0 ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs
|
|
170
|
+
resolve(tracker);
|
|
171
|
+
});
|
|
240
172
|
}
|
|
241
173
|
}
|
|
242
174
|
|
|
243
175
|
// app.controller.ts
|
|
244
176
|
import { ThrottlerBehindProxyGuard } from './throttler-behind-proxy.guard';
|
|
177
|
+
|
|
245
178
|
@UseGuards(ThrottlerBehindProxyGuard)
|
|
246
179
|
```
|
|
247
180
|
|
|
248
|
-
|
|
181
|
+
> info **Hint** You can find the API of the `req` Request object for express [here](https://expressjs.com/en/api.html#req.ips) and for fastify [here](https://www.fastify.io/docs/latest/Reference/Request/).
|
|
249
182
|
|
|
250
|
-
|
|
183
|
+
#### Websockets
|
|
251
184
|
|
|
252
|
-
|
|
185
|
+
This module can work with websockets, but it requires some class extension. You can extend the `ThrottlerGuard` and override the `handleRequest` method like so:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
253
188
|
@Injectable()
|
|
254
189
|
export class WsThrottlerGuard extends ThrottlerGuard {
|
|
255
|
-
async handleRequest(
|
|
190
|
+
async handleRequest(
|
|
191
|
+
context: ExecutionContext,
|
|
192
|
+
limit: number,
|
|
193
|
+
ttl: number,
|
|
194
|
+
throttler: ThrottlerOptions,
|
|
195
|
+
): Promise<boolean> {
|
|
256
196
|
const client = context.switchToWs().getClient();
|
|
257
|
-
|
|
258
|
-
const
|
|
259
|
-
.map((key) => client[key])
|
|
260
|
-
.filter((obj) => obj)
|
|
261
|
-
.shift().remoteAddress;
|
|
262
|
-
const key = this.generateKey(context, ip);
|
|
197
|
+
const ip = client._socket.remoteAddress;
|
|
198
|
+
const key = this.generateKey(context, ip, throttler.name);
|
|
263
199
|
const { totalHits } = await this.storageService.increment(key, ttl);
|
|
264
200
|
|
|
265
201
|
if (totalHits > limit) {
|
|
@@ -271,33 +207,173 @@ export class WsThrottlerGuard extends ThrottlerGuard {
|
|
|
271
207
|
}
|
|
272
208
|
```
|
|
273
209
|
|
|
274
|
-
|
|
210
|
+
> info **Hint** If you are using ws, it is necessary to replace the `_socket` with `conn`
|
|
211
|
+
|
|
212
|
+
There's a few things to keep in mind when working with WebSockets:
|
|
275
213
|
|
|
276
|
-
-
|
|
277
|
-
- When a limit is reached, Nest will emit an `exception` event, so make sure there is a listener ready for this
|
|
214
|
+
- Guard cannot be registered with the `APP_GUARD` or `app.useGlobalGuards()`
|
|
215
|
+
- When a limit is reached, Nest will emit an `exception` event, so make sure there is a listener ready for this
|
|
278
216
|
|
|
279
|
-
|
|
217
|
+
> info **Hint** If you are using the `@nestjs/platform-ws` package you can use `client._socket.remoteAddress` instead.
|
|
280
218
|
|
|
281
|
-
|
|
219
|
+
#### GraphQL
|
|
282
220
|
|
|
283
|
-
|
|
284
|
-
the default for Nest, but the [`apollo-server-fastify`](https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-fastify) package does not currently support passing `res` to the `context`, meaning headers cannot be properly set.
|
|
285
|
-
- When configuring your `GraphQLModule`, you need to pass an option for `context` in the form
|
|
286
|
-
of `({ req, res}) => ({ req, res })`. This will allow access to the Express Request and Response
|
|
287
|
-
objects, allowing for the reading and writing of headers.
|
|
288
|
-
- You must add in some additional context switching to get the `ExecutionContext` to pass back values correctly (or you can override the method entirely)
|
|
221
|
+
The `ThrottlerGuard` can also be used to work with GraphQL requests. Again, the guard can be extended, but this time the `getRequestResponse` method will be overridden
|
|
289
222
|
|
|
290
|
-
```
|
|
223
|
+
```typescript
|
|
291
224
|
@Injectable()
|
|
292
225
|
export class GqlThrottlerGuard extends ThrottlerGuard {
|
|
293
226
|
getRequestResponse(context: ExecutionContext) {
|
|
294
227
|
const gqlCtx = GqlExecutionContext.create(context);
|
|
295
228
|
const ctx = gqlCtx.getContext();
|
|
296
|
-
return { req: ctx.req, res: ctx.res };
|
|
229
|
+
return { req: ctx.req, res: ctx.res };
|
|
297
230
|
}
|
|
298
231
|
}
|
|
299
232
|
```
|
|
300
233
|
|
|
234
|
+
However, when using Apollo Express/Fastify or Mercurius, it's important to configure the context correctly in the GraphQLModule to avoid any problems.
|
|
235
|
+
|
|
236
|
+
#### Apollo Server (for Express):
|
|
237
|
+
|
|
238
|
+
For Apollo Server running on Express, you can set up the context in your GraphQLModule configuration as follows:
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
GraphQLModule.forRoot({
|
|
242
|
+
// ... other GraphQL module options
|
|
243
|
+
context: ({ req, res }) => ({ req, res }),
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
#### Apollo Server (for Fastify) & Mercurius:
|
|
248
|
+
|
|
249
|
+
When using Apollo Server with Fastify or Mercurius, you need to configure the context differently. You should use request and reply objects. Here's an example:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
GraphQLModule.forRoot({
|
|
253
|
+
// ... other GraphQL module options
|
|
254
|
+
context: (request, reply) => ({ request, reply }),
|
|
255
|
+
});
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
#### Configuration
|
|
259
|
+
|
|
260
|
+
The following options are valid for the object passed to the array of the `ThrottlerModule`'s options:
|
|
261
|
+
|
|
262
|
+
<table>
|
|
263
|
+
<tr>
|
|
264
|
+
<td><code>name</code></td>
|
|
265
|
+
<td>the name for internal tracking of which throttler set is being used. Defaults to `default` if not passed</td>
|
|
266
|
+
</tr>
|
|
267
|
+
<tr>
|
|
268
|
+
<td><code>ttl</code></td>
|
|
269
|
+
<td>the number of milliseconds that each request will last in storage</td>
|
|
270
|
+
</tr>
|
|
271
|
+
<tr>
|
|
272
|
+
<td><code>limit</code></td>
|
|
273
|
+
<td>the maximum number of requests within the TTL limit</td>
|
|
274
|
+
</tr>
|
|
275
|
+
<tr>
|
|
276
|
+
<td><code>ignoreUserAgents</code></td>
|
|
277
|
+
<td>an array of regular expressions of user-agents to ignore when it comes to throttling requests</td>
|
|
278
|
+
</tr>
|
|
279
|
+
<tr>
|
|
280
|
+
<td><code>skipIf</code></td>
|
|
281
|
+
<td>a function that takes in the <code>ExecutionContext</code> and returns a <code>boolean</code> to short circuit the throttler logic. Like <code>@SkipThrottler()</code>, but based on the request</td>
|
|
282
|
+
</tr>
|
|
283
|
+
</table>
|
|
284
|
+
|
|
285
|
+
If you need to set up storages instead, or want to use a some of the above options in a more global sense, applying to each throttler set, you can pass the options above via the `throttlers` option key and use the below table
|
|
286
|
+
|
|
287
|
+
<table>
|
|
288
|
+
<tr>
|
|
289
|
+
<td><code>storage</code></td>
|
|
290
|
+
<td>a custom storage service for where the throttling should be kept track. <a href="/security/rate-limiting#storages">See here.</a></td>
|
|
291
|
+
</tr>
|
|
292
|
+
<tr>
|
|
293
|
+
<td><code>ignoreUserAgents</code></td>
|
|
294
|
+
<td>an array of regular expressions of user-agents to ignore when it comes to throttling requests</td>
|
|
295
|
+
</tr>
|
|
296
|
+
<tr>
|
|
297
|
+
<td><code>skipIf</code></td>
|
|
298
|
+
<td>a function that takes in the <code>ExecutionContext</code> and returns a <code>boolean</code> to short circuit the throttler logic. Like <code>@SkipThrottler()</code>, but based on the request</td>
|
|
299
|
+
</tr>
|
|
300
|
+
<tr>
|
|
301
|
+
<td><code>throttlers</code></td>
|
|
302
|
+
<td>an array of throttler sets, defined using the table above</td>
|
|
303
|
+
</tr>
|
|
304
|
+
</table>
|
|
305
|
+
|
|
306
|
+
#### Async Configuration
|
|
307
|
+
|
|
308
|
+
You may want to get your rate-limiting configuration asynchronously instead of synchronously. You can use the `forRootAsync()` method, which allows for dependency injection and `async` methods.
|
|
309
|
+
|
|
310
|
+
One approach would be to use a factory function:
|
|
311
|
+
|
|
312
|
+
```typescript
|
|
313
|
+
@Module({
|
|
314
|
+
imports: [
|
|
315
|
+
ThrottlerModule.forRootAsync({
|
|
316
|
+
imports: [ConfigModule],
|
|
317
|
+
inject: [ConfigService],
|
|
318
|
+
useFactory: (config: ConfigService) => [
|
|
319
|
+
{
|
|
320
|
+
ttl: config.get('THROTTLE_TTL'),
|
|
321
|
+
limit: config.get('THROTTLE_LIMIT'),
|
|
322
|
+
},
|
|
323
|
+
],
|
|
324
|
+
}),
|
|
325
|
+
],
|
|
326
|
+
})
|
|
327
|
+
export class AppModule {}
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
You can also use the `useClass` syntax:
|
|
331
|
+
|
|
332
|
+
```typescript
|
|
333
|
+
@Module({
|
|
334
|
+
imports: [
|
|
335
|
+
ThrottlerModule.forRootAsync({
|
|
336
|
+
imports: [ConfigModule],
|
|
337
|
+
useClass: ThrottlerConfigService,
|
|
338
|
+
}),
|
|
339
|
+
],
|
|
340
|
+
})
|
|
341
|
+
export class AppModule {}
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
This is doable, as long as `ThrottlerConfigService` implements the interface `ThrottlerOptionsFactory`.
|
|
345
|
+
|
|
346
|
+
#### Storages
|
|
347
|
+
|
|
348
|
+
The built in storage is an in memory cache that keeps track of the requests made until they have passed the TTL set by the global options. You can drop in your own storage option to the `storage` option of the `ThrottlerModule` so long as the class implements the `ThrottlerStorage` interface.
|
|
349
|
+
|
|
350
|
+
> info **Note** `ThrottlerStorage` can be imported from `@nestjs/throttler`.
|
|
351
|
+
|
|
352
|
+
#### Time Helpers
|
|
353
|
+
|
|
354
|
+
There are a couple of helper methods to make the timings more readable if you prefer to use them over the direct definition. `@nestjs/throttler` exports five different helpers, `seconds`, `minutes`, `hours`, `days`, and `weeks`. To use them, simply call `seconds(5)` or any of the other helpers, and the correct number of milliseconds will be returned.
|
|
355
|
+
|
|
356
|
+
#### Migration Guide
|
|
357
|
+
|
|
358
|
+
For most people, wrapping your options in an array will be enough.
|
|
359
|
+
|
|
360
|
+
If you are using a custom storage, you should wrap you `ttl` and `limit` in an
|
|
361
|
+
array and assign it to the `throttlers` property of the options object.
|
|
362
|
+
|
|
363
|
+
Any `@ThrottleSkip()` should now take in an object with `string: boolean` props.
|
|
364
|
+
The strings are the names of the throttlers. If you do not have a name, pass the
|
|
365
|
+
string `'default'`, as this is what will be used under the hood otherwise.
|
|
366
|
+
|
|
367
|
+
Any `@Throttle()` decorators should also now take in an object with string keys,
|
|
368
|
+
relating to the names of the throttler contexts (again, `'default'` if no name)
|
|
369
|
+
and values of objects that have `limit` and `ttl` keys.
|
|
370
|
+
|
|
371
|
+
> Warning **Important** The `ttl` is now in **milliseconds**. If you want to keep your ttl
|
|
372
|
+
> in seconds for readability, use the `seconds` helper from this package. It just
|
|
373
|
+
> multiplies the ttl by 1000 to make it in milliseconds.
|
|
374
|
+
|
|
375
|
+
For more info, see the [Changelog](https://github.com/nestjs/throttler/blob/master/CHANGELOG.md#500)
|
|
376
|
+
|
|
301
377
|
## Community Storage Providers
|
|
302
378
|
|
|
303
379
|
- [Redis](https://github.com/kkoomen/nestjs-throttler-storage-redis)
|
|
@@ -308,3 +384,5 @@ Feel free to submit a PR with your custom storage provider being added to this l
|
|
|
308
384
|
## License
|
|
309
385
|
|
|
310
386
|
Nest is [MIT licensed](LICENSE).
|
|
387
|
+
|
|
388
|
+
<p align="right"><a href="#toc">🔼 Back to TOC</a></p>
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -25,4 +25,5 @@ var throttler_providers_1 = require("./throttler.providers");
|
|
|
25
25
|
Object.defineProperty(exports, "getOptionsToken", { enumerable: true, get: function () { return throttler_providers_1.getOptionsToken; } });
|
|
26
26
|
Object.defineProperty(exports, "getStorageToken", { enumerable: true, get: function () { return throttler_providers_1.getStorageToken; } });
|
|
27
27
|
__exportStar(require("./throttler.service"), exports);
|
|
28
|
+
__exportStar(require("./utilities"), exports);
|
|
28
29
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,uEAAqD;AACrD,gEAA8C;AAC9C,wDAAsC;AACtC,wDAAsC;AACtC,oDAAkC;AAClC,qDAAmC;AACnC,6DAAyE;AAAhE,sHAAA,eAAe,OAAA;AAAE,sHAAA,eAAe,OAAA;AACzC,sDAAoC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,uEAAqD;AACrD,gEAA8C;AAC9C,wDAAsC;AACtC,wDAAsC;AACtC,oDAAkC;AAClC,qDAAmC;AACnC,6DAAyE;AAAhE,sHAAA,eAAe,OAAA;AAAE,sHAAA,eAAe,OAAA;AACzC,sDAAoC;AACpC,8CAA4B"}
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { ExecutionContext, ModuleMetadata, Type } from '@nestjs/common/interfaces';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { ThrottlerStorage } from './throttler-storage.interface';
|
|
3
|
+
export type Resolvable<T extends number | string | boolean> = T | ((context: ExecutionContext) => T | Promise<T>);
|
|
4
|
+
export interface ThrottlerOptions {
|
|
5
|
+
name?: string;
|
|
6
|
+
limit: Resolvable<number>;
|
|
7
|
+
ttl: Resolvable<number>;
|
|
5
8
|
ignoreUserAgents?: RegExp[];
|
|
6
|
-
storage?: any;
|
|
7
9
|
skipIf?: (context: ExecutionContext) => boolean;
|
|
8
10
|
}
|
|
11
|
+
export type ThrottlerModuleOptions = Array<ThrottlerOptions> | {
|
|
12
|
+
skipIf?: (context: ExecutionContext) => boolean;
|
|
13
|
+
ignoreUserAgents?: RegExp[];
|
|
14
|
+
storage?: ThrottlerStorage;
|
|
15
|
+
throttlers: Array<ThrottlerOptions>;
|
|
16
|
+
};
|
|
9
17
|
export interface ThrottlerOptionsFactory {
|
|
10
18
|
createThrottlerOptions(): Promise<ThrottlerModuleOptions> | ThrottlerModuleOptions;
|
|
11
19
|
}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { ThrottlerStorageOptions } from './throttler-storage-options.interface';
|
|
2
1
|
import { ThrottlerStorageRecord } from './throttler-storage-record.interface';
|
|
3
2
|
export interface ThrottlerStorage {
|
|
4
|
-
storage: Record<string, ThrottlerStorageOptions>;
|
|
5
3
|
increment(key: string, ttl: number): Promise<ThrottlerStorageRecord>;
|
|
6
4
|
}
|
|
7
5
|
export declare const ThrottlerStorage: unique symbol;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler-storage.interface.js","sourceRoot":"","sources":["../src/throttler-storage.interface.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"throttler-storage.interface.js","sourceRoot":"","sources":["../src/throttler-storage.interface.ts"],"names":[],"mappings":";;;AAUa,QAAA,gBAAgB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC"}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { Resolvable } from './throttler-module-options.interface';
|
|
2
|
+
interface ThrottlerMethodOrControllerOptions {
|
|
3
|
+
limit?: Resolvable<number>;
|
|
4
|
+
ttl?: Resolvable<number>;
|
|
5
|
+
}
|
|
6
|
+
export declare const Throttle: (options: Record<string, ThrottlerMethodOrControllerOptions>) => MethodDecorator & ClassDecorator;
|
|
7
|
+
export declare const SkipThrottle: (skip?: Record<string, boolean>) => MethodDecorator & ClassDecorator;
|
|
3
8
|
export declare const InjectThrottlerOptions: () => PropertyDecorator & ParameterDecorator;
|
|
4
9
|
export declare const InjectThrottlerStorage: () => PropertyDecorator & ParameterDecorator;
|
|
10
|
+
export {};
|
|
@@ -4,29 +4,31 @@ exports.InjectThrottlerStorage = exports.InjectThrottlerOptions = exports.SkipTh
|
|
|
4
4
|
const common_1 = require("@nestjs/common");
|
|
5
5
|
const throttler_constants_1 = require("./throttler.constants");
|
|
6
6
|
const throttler_providers_1 = require("./throttler.providers");
|
|
7
|
-
function setThrottlerMetadata(target,
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
function setThrottlerMetadata(target, options) {
|
|
8
|
+
for (const name in options) {
|
|
9
|
+
Reflect.defineMetadata(throttler_constants_1.THROTTLER_TTL + name, options[name].ttl, target);
|
|
10
|
+
Reflect.defineMetadata(throttler_constants_1.THROTTLER_LIMIT + name, options[name].limit, target);
|
|
11
|
+
}
|
|
10
12
|
}
|
|
11
|
-
const Throttle = (
|
|
13
|
+
const Throttle = (options) => {
|
|
12
14
|
return (target, propertyKey, descriptor) => {
|
|
13
15
|
if (descriptor) {
|
|
14
|
-
setThrottlerMetadata(descriptor.value,
|
|
16
|
+
setThrottlerMetadata(descriptor.value, options);
|
|
15
17
|
return descriptor;
|
|
16
18
|
}
|
|
17
|
-
setThrottlerMetadata(target,
|
|
19
|
+
setThrottlerMetadata(target, options);
|
|
18
20
|
return target;
|
|
19
21
|
};
|
|
20
22
|
};
|
|
21
23
|
exports.Throttle = Throttle;
|
|
22
|
-
const SkipThrottle = (skip = true) => {
|
|
24
|
+
const SkipThrottle = (skip = { default: true }) => {
|
|
23
25
|
return (target, propertyKey, descriptor) => {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
var _a;
|
|
27
|
+
const reflectionTarget = (_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) !== null && _a !== void 0 ? _a : target;
|
|
28
|
+
for (const key in skip) {
|
|
29
|
+
Reflect.defineMetadata(throttler_constants_1.THROTTLER_SKIP + key, skip[key], reflectionTarget);
|
|
27
30
|
}
|
|
28
|
-
|
|
29
|
-
return target;
|
|
31
|
+
return descriptor !== null && descriptor !== void 0 ? descriptor : target;
|
|
30
32
|
};
|
|
31
33
|
};
|
|
32
34
|
exports.SkipThrottle = SkipThrottle;
|