@nestjs/throttler 1.2.1 → 3.0.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,115 @@
1
+ # [2.0.0](https://github.com/nestjs/throttler/compare/v1.2.1...v2.0.0) (2021-07-09)
2
+
3
+ ## 3.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - c9fcd51: Upgrade nest version to v9. No breaking changes in direct code, but in nest v9 upgrade
8
+
9
+ ## 2.0.1
10
+
11
+ ### Patch Changes
12
+
13
+ - cf50808: fix memory leak for timeoutIds array. Before this, the timeoutIds array would not be trimmed and would grow until out of memory. Now ids are properly removed on timeout.
14
+
15
+ ### Features
16
+
17
+ - adding in a comment about version ([b13bf53](https://github.com/nestjs/throttler/commit/b13bf53542236ba6b05ac537b7a677e1644a0407))
18
+
19
+ ### BREAKING CHANGES
20
+
21
+ - v2 and above is now being developed specificially for
22
+ nest v8 and could have some unforseen side effects with Nest v7. use with
23
+ v7 at your own risk.
24
+
25
+ ## [1.2.1](https://github.com/nestjs/throttler/compare/v1.2.0...v1.2.1) (2021-07-09)
26
+
27
+ ### Performance Improvements
28
+
29
+ - upgrade to nest v8 ([cb5dd91](https://github.com/nestjs/throttler/commit/cb5dd913e9fcc482cd74f2d49085b98dac630215))
30
+
31
+ # [0.3.0](https://github.com/jmcdo29/nestjs-throttler/compare/0.2.3...0.3.0) (2020-11-10)
32
+
33
+ ### Bug Fixes
34
+
35
+ - **module:** async register is now `forRootAsync` ([a1c6ace](https://github.com/jmcdo29/nestjs-throttler/commit/a1c6acef472e9d2368f2139e6b789ef184a7d952))
36
+
37
+ ## [0.2.3](https://github.com/jmcdo29/nestjs-throttler/compare/0.2.2...0.2.3) (2020-08-06)
38
+
39
+ ### Features
40
+
41
+ - **ws:** allows for optional use of @nestjs/websocket ([f437614](https://github.com/jmcdo29/nestjs-throttler/commit/f437614cab5aebfdfdb4d5884f45b58b16d5a140))
42
+
43
+ ## [0.2.2](https://github.com/jmcdo29/nestjs-throttler/compare/0.2.1...0.2.2) (2020-06-12)
44
+
45
+ ### Bug Fixes
46
+
47
+ - moves userAgent check to http handler ([87183af](https://github.com/jmcdo29/nestjs-throttler/commit/87183af8fc189d7d5c8237832089138a0b40589b))
48
+
49
+ ### Features
50
+
51
+ - **decorator:** add setThrottlerMetadata() function back ([ea31a9c](https://github.com/jmcdo29/nestjs-throttler/commit/ea31a9c86b82550e2d43f3433ec618785cf2b34a))
52
+ - **graphql:** implements graphql limiter ([40eaff1](https://github.com/jmcdo29/nestjs-throttler/commit/40eaff16dae5c0279001e56ff64a2b540d82a3c7))
53
+ - Add support for ws (websockets) ([a745295](https://github.com/jmcdo29/nestjs-throttler/commit/a74529517f989c43d77c9a63712e82244ebeefcd))
54
+ - Add support for ws (websockets) ([8103a5a](https://github.com/jmcdo29/nestjs-throttler/commit/8103a5a11c1916f05f8c44e302ba93a98d7cb77d))
55
+ - Make storage methods async ([92cd4eb](https://github.com/jmcdo29/nestjs-throttler/commit/92cd4ebf507b3bed4efbaeb7bb47bd1738a62dc3))
56
+ - **exception:** Use const instead of duplicated string ([f95da2c](https://github.com/jmcdo29/nestjs-throttler/commit/f95da2c4fc787c7c5e525672d668745bc1f2301d))
57
+ - **guard:** Add default case for context.getType() switch ([ff46d57](https://github.com/jmcdo29/nestjs-throttler/commit/ff46d57508c4b446918ccd75f704d0eed1ae352f))
58
+ - Implement basic support for websocket ([3a0cf2e](https://github.com/jmcdo29/nestjs-throttler/commit/3a0cf2ed70c7abbe02e9d96f26ab2c81b3c7bb2f))
59
+
60
+ ## [0.2.1](https://github.com/jmcdo29/nestjs-throttler/compare/0.2.0...0.2.1) (2020-06-09)
61
+
62
+ ### Features
63
+
64
+ - add support for ignoreUserAgents option ([1ab5e17](https://github.com/jmcdo29/nestjs-throttler/commit/1ab5e17a25a95ec14910e199726eac07f66f4475))
65
+
66
+ # [0.2.0](https://github.com/jmcdo29/nestjs-throttler/compare/0.1.1...0.2.0) (2020-06-09)
67
+
68
+ ### Bug Fixes
69
+
70
+ - make core module global and export core module inside ThrottlerModule ([1f4df42](https://github.com/jmcdo29/nestjs-throttler/commit/1f4df42a5fc9a6f75c398bbb6a3f9ebaec6bc80f))
71
+
72
+ ### Features
73
+
74
+ - makes options required in forRoot and forRootAsync ([14e272a](https://github.com/jmcdo29/nestjs-throttler/commit/14e272a842a90db93dd9e8c60c936fbcf0bcd3b7))
75
+ - remove global guard and require user to implement it manually ([840eae4](https://github.com/jmcdo29/nestjs-throttler/commit/840eae4643867390bc598937b20e132257e9b018))
76
+
77
+ ## [0.1.1](https://github.com/jmcdo29/nestjs-throttler/compare/0.1.0...0.1.1) (2020-06-07)
78
+
79
+ ### Bug Fixes
80
+
81
+ - **interface:** fixes the storage interface to be async ([f7565d9](https://github.com/jmcdo29/nestjs-throttler/commit/f7565d9029baf4d7687f0913046f555d17cde44b))
82
+
83
+ # 0.1.0 (2020-06-07)
84
+
85
+ ### Bug Fixes
86
+
87
+ - adds back AppModule to allow for running server for tests ([5af229b](https://github.com/jmcdo29/nestjs-throttler/commit/5af229ba69527daf3662b1899ed985fa9404251b))
88
+ - updates some types ([b26fc06](https://github.com/jmcdo29/nestjs-throttler/commit/b26fc06841a430e5728cde6276515130b89a7289))
89
+ - updates storage interface to use number ([339f29c](https://github.com/jmcdo29/nestjs-throttler/commit/339f29c12b4720a7376ec042988f73460172b32e))
90
+ - updates tests and resolves comments from pr ([ee87e05](https://github.com/jmcdo29/nestjs-throttler/commit/ee87e05e2f5eb61b00b423d6394be9a131f84f8a))
91
+ - **.gitignore:** Ignore all dist and node_modules rather than root-level only ([d9609af](https://github.com/jmcdo29/nestjs-throttler/commit/d9609afb9cf3561b84082ac9a3e2e26ddcbb2117))
92
+ - **guard:** Change RateLimit header prefix to X-RateLimit ([328c0a3](https://github.com/jmcdo29/nestjs-throttler/commit/328c0a3c1009fdc65820125c2145de65aebd3fee))
93
+ - **guard:** Change RateLimit header prefix to X-RateLimit ([3903885](https://github.com/jmcdo29/nestjs-throttler/commit/3903885df9eaac0d966c5b8207fae26b62f337f3))
94
+ - **guard:** guard now binds globally without the use of @UseGuards() ([4022447](https://github.com/jmcdo29/nestjs-throttler/commit/40224475d27f1ec0cf792225bbc18df33ab14cc2))
95
+ - **guard:** guard now binds globally without the use of @UseGuards() ([3ca146d](https://github.com/jmcdo29/nestjs-throttler/commit/3ca146d41afa71e3c68b73d8706e7431f929a85a))
96
+ - **guard:** Prevent RateLimit-Remaining from going below 0 ([25e33c8](https://github.com/jmcdo29/nestjs-throttler/commit/25e33c882007892a3285c92449aa5bc0840a8909))
97
+ - **guard:** Prevent RateLimit-Remaining from going below 0 ([74b1668](https://github.com/jmcdo29/nestjs-throttler/commit/74b166888ab283281a964d6c64b94224e2f96ba4))
98
+ - **guard:** Use the correct approach to check for excluded routes ([38eac3c](https://github.com/jmcdo29/nestjs-throttler/commit/38eac3ca3bdad0b4b266587bc4b0287f3f69f640))
99
+ - **guard:** Use the correct approach to check for excluded routes ([912813f](https://github.com/jmcdo29/nestjs-throttler/commit/912813f49cc98e8fbd2643650d22ea8cc88c77ae))
100
+ - req.method value in httpPromise ([b9ee26e](https://github.com/jmcdo29/nestjs-throttler/commit/b9ee26e5e888e4d4f220e91adc996ade764f7002))
101
+
102
+ ### Features
103
+
104
+ - Swap excludeRoutes for @SkipThrottle() decorator ([16d6fac](https://github.com/jmcdo29/nestjs-throttler/commit/16d6facd5e8f648620fa47e372078db37472f619))
105
+ - **fastify:** updates guard to work for fastify ([bc678a3](https://github.com/jmcdo29/nestjs-throttler/commit/bc678a363c367d132a90a2a4282e3f033f526e00))
106
+ - Implement ignoreRoutes functionality ([7b8ab42](https://github.com/jmcdo29/nestjs-throttler/commit/7b8ab4273fffafc0dd0571393d8c0faf89afc42f))
107
+ - **package.json:** Add --watch to start:dev script ([3c4c28a](https://github.com/jmcdo29/nestjs-throttler/commit/3c4c28abbb324e064f65b284f1a99683cd02030b))
108
+ - Implement ignoreRoutes functionality ([75f870c](https://github.com/jmcdo29/nestjs-throttler/commit/75f870c5b49e4d22c70519d28f8efffc1da288eb))
109
+ - **module:** implements start of limiter module ([35dbff5](https://github.com/jmcdo29/nestjs-throttler/commit/35dbff5d30e7a1385a4f4cf688992017eb7e0566))
110
+ - **package.json:** Add --watch to start:dev script ([a6b441c](https://github.com/jmcdo29/nestjs-throttler/commit/a6b441cad221b7eee52be0ba81c66fca81853c4f))
111
+ - Add global ThrottlerGuard ([9a84aff](https://github.com/jmcdo29/nestjs-throttler/commit/9a84afff5d57a16731d021cb47d60c2b4d02eb02))
112
+ - adds httpromise for async/await http calls in tests ([70210c7](https://github.com/jmcdo29/nestjs-throttler/commit/70210c76173aabfd5f85f5a24e624e7c4c010ae2))
113
+ - Rename certain variables to use the THROTTLER prefix ([6a21b21](https://github.com/jmcdo29/nestjs-throttler/commit/6a21b216a2738aa470e2138d44053ba8413ce117))
114
+ - Setup example app ([df6b5f6](https://github.com/jmcdo29/nestjs-throttler/commit/df6b5f633ebbb4770d3eb9e72e8075cbe6b2f78a))
115
+ - Setup example app ([30c7576](https://github.com/jmcdo29/nestjs-throttler/commit/30c75764fd20f3afe7a3f7533a3f4f08d275a741))
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  # The MIT License
2
2
 
3
- Copyright 2019 Jay McDoniel, contributors
3
+ Copyright 2019-2022 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,5 +1,5 @@
1
1
  <p align="center">
2
- <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
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
4
 
5
5
  [travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
@@ -31,9 +31,21 @@ For an overview of the community storage providers, see [Community Storage Provi
31
31
 
32
32
  This package comes with a couple of goodies that should be mentioned, first is the `ThrottlerModule`.
33
33
 
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ $ npm i --save @nestjs/throttler
39
+ ```
40
+
41
+ ## Versions
42
+
43
+ `@nestjs/throttler@^1` is compatible with Nest v7 while `@nestjs/throttler@^2` is compatible with Nest v7 and Nest v8, but it is suggested to be used with only v8 in case of breaking changes against v7 that are unseen.
44
+
34
45
  ## Table of Contents
35
46
 
36
47
  - [Description](#description)
48
+ - [Versions](#versions)
37
49
  - [Table of Contents](#table-of-contents)
38
50
  - [Usage](#usage)
39
51
  - [ThrottlerModule](#throttlermodule)
@@ -139,7 +151,7 @@ export class AppController {
139
151
  @Throttle(limit: number = 30, ttl: number = 60)
140
152
  ```
141
153
 
142
- This decorator will set THROTTLER_LIMIT and THROTTLER_TTL metadatas on the
154
+ This decorator will set `THROTTLER_LIMIT` and `THROTTLER_TTL` metadatas on the
143
155
  route, for retrieval from the `Reflector` class. Can be applied to controllers
144
156
  and routes.
145
157
 
@@ -213,7 +225,24 @@ So long as the Storage service implements this interface, it should be usable by
213
225
 
214
226
  ### Proxies
215
227
 
216
- If you are working behind a proxy, check the specific HTTP adapter options ([express](http://expressjs.com/en/guide/behind-proxies.html) and [fastify](https://www.fastify.io/docs/latest/Server/#trustproxy)) for the `trust proxy` option and enable it. Doing so will allow you to get the original IP address from the `X-Forward-For` header, and you can override the `getTracker()` method to pull the value from the header rather than from `req.ip`
228
+ If you are working behind a proxy, check the specific HTTP adapter options ([express](http://expressjs.com/en/guide/behind-proxies.html) and [fastify](https://www.fastify.io/docs/latest/Server/#trustproxy)) for the `trust proxy` option and enable it. Doing so will allow you to get the original IP address from the `X-Forward-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:
229
+
230
+ ```ts
231
+ // throttler-behind-proxy.guard.ts
232
+ import { ThrottlerGuard } from '@nestjs/throttler';
233
+ import { Injectable } from '@nestjs/common';
234
+
235
+ @Injectable()
236
+ export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
237
+ protected getTracker(req: Record<string, any>): string {
238
+ return req.ips.length ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs
239
+ }
240
+ }
241
+
242
+ // app.controller.ts
243
+ import { ThrottlerBehindProxyGuard } from './throttler-behind-proxy.guard';
244
+ @UseGuards(ThrottlerBehindProxyGuard)
245
+ ```
217
246
 
218
247
  ### Working with Websockets
219
248
 
@@ -264,7 +293,7 @@ export class GqlThrottlerGuard extends ThrottlerGuard {
264
293
  getRequestResponse(context: ExecutionContext) {
265
294
  const gqlCtx = GqlExecutionContext.create(context);
266
295
  const ctx = gqlCtx.getContext();
267
- return { req, ctx.req, res: ctx.res }; // ctx.request and ctx.reply for fastify
296
+ return { req: ctx.req, res: ctx.res }; // ctx.request and ctx.reply for fastify
268
297
  }
269
298
  }
270
299
  ```
@@ -274,3 +303,7 @@ export class GqlThrottlerGuard extends ThrottlerGuard {
274
303
  - [Redis](https://github.com/kkoomen/nestjs-throttler-storage-redis)
275
304
 
276
305
  Feel free to submit a PR with your custom storage provider being added to this list.
306
+
307
+ ## License
308
+
309
+ Nest is [MIT licensed](LICENSE).
package/dist/index.js CHANGED
@@ -1,47 +1,28 @@
1
- 'use strict';
2
- var __createBinding =
3
- (this && this.__createBinding) ||
4
- (Object.create
5
- ? function (o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- Object.defineProperty(o, k2, {
8
- enumerable: true,
9
- get: function () {
10
- return m[k];
11
- },
12
- });
13
- }
14
- : function (o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- });
18
- var __exportStar =
19
- (this && this.__exportStar) ||
20
- function (m, exports) {
21
- for (var p in m)
22
- if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p))
23
- __createBinding(exports, m, p);
24
- };
25
- Object.defineProperty(exports, '__esModule', { value: true });
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
26
17
  exports.getStorageToken = exports.getOptionsToken = void 0;
27
- __exportStar(require('./throttler-module-options.interface'), exports);
28
- __exportStar(require('./throttler-storage.interface'), exports);
29
- __exportStar(require('./throttler.decorator'), exports);
30
- __exportStar(require('./throttler.exception'), exports);
31
- __exportStar(require('./throttler.guard'), exports);
32
- __exportStar(require('./throttler.module'), exports);
33
- var throttler_providers_1 = require('./throttler.providers');
34
- Object.defineProperty(exports, 'getOptionsToken', {
35
- enumerable: true,
36
- get: function () {
37
- return throttler_providers_1.getOptionsToken;
38
- },
39
- });
40
- Object.defineProperty(exports, 'getStorageToken', {
41
- enumerable: true,
42
- get: function () {
43
- return throttler_providers_1.getStorageToken;
44
- },
45
- });
46
- __exportStar(require('./throttler.service'), exports);
47
- //# sourceMappingURL=index.js.map
18
+ __exportStar(require("./throttler-module-options.interface"), exports);
19
+ __exportStar(require("./throttler-storage.interface"), exports);
20
+ __exportStar(require("./throttler.decorator"), exports);
21
+ __exportStar(require("./throttler.exception"), exports);
22
+ __exportStar(require("./throttler.guard"), exports);
23
+ __exportStar(require("./throttler.module"), exports);
24
+ var throttler_providers_1 = require("./throttler.providers");
25
+ Object.defineProperty(exports, "getOptionsToken", { enumerable: true, get: function () { return throttler_providers_1.getOptionsToken; } });
26
+ Object.defineProperty(exports, "getStorageToken", { enumerable: true, get: function () { return throttler_providers_1.getStorageToken; } });
27
+ __exportStar(require("./throttler.service"), exports);
28
+ //# 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"}
@@ -1,3 +1,3 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- //# sourceMappingURL=throttler-module-options.interface.js.map
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=throttler-module-options.interface.js.map
@@ -1,5 +1,5 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ThrottlerStorage = void 0;
4
4
  exports.ThrottlerStorage = Symbol('ThrottlerStorage');
5
- //# sourceMappingURL=throttler-storage.interface.js.map
5
+ //# sourceMappingURL=throttler-storage.interface.js.map
@@ -1,12 +1,8 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.THROTTLER_SKIP =
4
- exports.THROTTLER_OPTIONS =
5
- exports.THROTTLER_TTL =
6
- exports.THROTTLER_LIMIT =
7
- void 0;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.THROTTLER_SKIP = exports.THROTTLER_OPTIONS = exports.THROTTLER_TTL = exports.THROTTLER_LIMIT = void 0;
8
4
  exports.THROTTLER_LIMIT = 'THROTTLER:LIMIT';
9
5
  exports.THROTTLER_TTL = 'THROTTLER:TTL';
10
6
  exports.THROTTLER_OPTIONS = 'THROTTLER:MODULE_OPTIONS';
11
7
  exports.THROTTLER_SKIP = 'THROTTLER:SKIP';
12
- //# sourceMappingURL=throttler.constants.js.map
8
+ //# sourceMappingURL=throttler.constants.js.map
@@ -1,41 +1,37 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.InjectThrottlerStorage =
4
- exports.InjectThrottlerOptions =
5
- exports.SkipThrottle =
6
- exports.Throttle =
7
- void 0;
8
- const common_1 = require('@nestjs/common');
9
- const throttler_constants_1 = require('./throttler.constants');
10
- const throttler_providers_1 = require('./throttler.providers');
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectThrottlerStorage = exports.InjectThrottlerOptions = exports.SkipThrottle = exports.Throttle = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const throttler_constants_1 = require("./throttler.constants");
6
+ const throttler_providers_1 = require("./throttler.providers");
11
7
  function setThrottlerMetadata(target, limit, ttl) {
12
- Reflect.defineMetadata(throttler_constants_1.THROTTLER_TTL, ttl, target);
13
- Reflect.defineMetadata(throttler_constants_1.THROTTLER_LIMIT, limit, target);
8
+ Reflect.defineMetadata(throttler_constants_1.THROTTLER_TTL, ttl, target);
9
+ Reflect.defineMetadata(throttler_constants_1.THROTTLER_LIMIT, limit, target);
14
10
  }
15
11
  const Throttle = (limit = 20, ttl = 60) => {
16
- return (target, propertyKey, descriptor) => {
17
- if (descriptor) {
18
- setThrottlerMetadata(descriptor.value, limit, ttl);
19
- return descriptor;
20
- }
21
- setThrottlerMetadata(target, limit, ttl);
22
- return target;
23
- };
12
+ return (target, propertyKey, descriptor) => {
13
+ if (descriptor) {
14
+ setThrottlerMetadata(descriptor.value, limit, ttl);
15
+ return descriptor;
16
+ }
17
+ setThrottlerMetadata(target, limit, ttl);
18
+ return target;
19
+ };
24
20
  };
25
21
  exports.Throttle = Throttle;
26
22
  const SkipThrottle = (skip = true) => {
27
- return (target, propertyKey, descriptor) => {
28
- if (descriptor) {
29
- Reflect.defineMetadata(throttler_constants_1.THROTTLER_SKIP, skip, descriptor.value);
30
- return descriptor;
31
- }
32
- Reflect.defineMetadata(throttler_constants_1.THROTTLER_SKIP, skip, target);
33
- return target;
34
- };
23
+ return (target, propertyKey, descriptor) => {
24
+ if (descriptor) {
25
+ Reflect.defineMetadata(throttler_constants_1.THROTTLER_SKIP, skip, descriptor.value);
26
+ return descriptor;
27
+ }
28
+ Reflect.defineMetadata(throttler_constants_1.THROTTLER_SKIP, skip, target);
29
+ return target;
30
+ };
35
31
  };
36
32
  exports.SkipThrottle = SkipThrottle;
37
- const InjectThrottlerOptions = () => common_1.Inject(throttler_providers_1.getOptionsToken());
33
+ const InjectThrottlerOptions = () => (0, common_1.Inject)((0, throttler_providers_1.getOptionsToken)());
38
34
  exports.InjectThrottlerOptions = InjectThrottlerOptions;
39
- const InjectThrottlerStorage = () => common_1.Inject(throttler_providers_1.getStorageToken());
35
+ const InjectThrottlerStorage = () => (0, common_1.Inject)((0, throttler_providers_1.getStorageToken)());
40
36
  exports.InjectThrottlerStorage = InjectThrottlerStorage;
41
- //# sourceMappingURL=throttler.decorator.js.map
37
+ //# sourceMappingURL=throttler.decorator.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.decorator.js","sourceRoot":"","sources":["../src/throttler.decorator.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AACxC,+DAAuF;AACvF,+DAAy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AAOK,MAAM,sBAAsB,GAAG,GAAG,EAAE,CAAC,IAAA,eAAM,EAAC,IAAA,qCAAe,GAAE,CAAC,CAAC;AAAzD,QAAA,sBAAsB,0BAAmC;AAO/D,MAAM,sBAAsB,GAAG,GAAG,EAAE,CAAC,IAAA,eAAM,EAAC,IAAA,qCAAe,GAAE,CAAC,CAAC;AAAzD,QAAA,sBAAsB,0BAAmC"}
@@ -1,12 +1,12 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ThrottlerException = exports.throttlerMessage = void 0;
4
- const common_1 = require('@nestjs/common');
4
+ const common_1 = require("@nestjs/common");
5
5
  exports.throttlerMessage = 'ThrottlerException: Too Many Requests';
6
6
  class ThrottlerException extends common_1.HttpException {
7
- constructor(message) {
8
- super(`${message || exports.throttlerMessage}`, common_1.HttpStatus.TOO_MANY_REQUESTS);
9
- }
7
+ constructor(message) {
8
+ super(`${message || exports.throttlerMessage}`, common_1.HttpStatus.TOO_MANY_REQUESTS);
9
+ }
10
10
  }
11
11
  exports.ThrottlerException = ThrottlerException;
12
- //# sourceMappingURL=throttler.exception.js.map
12
+ //# sourceMappingURL=throttler.exception.js.map
@@ -1,119 +1,94 @@
1
- 'use strict';
2
- var __decorate =
3
- (this && this.__decorate) ||
4
- function (decorators, target, key, desc) {
5
- var c = arguments.length,
6
- r =
7
- c < 3
8
- ? target
9
- : desc === null
10
- ? (desc = Object.getOwnPropertyDescriptor(target, key))
11
- : desc,
12
- d;
13
- if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function')
14
- r = Reflect.decorate(decorators, target, key, desc);
15
- else
16
- for (var i = decorators.length - 1; i >= 0; i--)
17
- if ((d = decorators[i]))
18
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
20
- };
21
- var __metadata =
22
- (this && this.__metadata) ||
23
- function (k, v) {
24
- if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function')
25
- return Reflect.metadata(k, v);
26
- };
27
- var __param =
28
- (this && this.__param) ||
29
- function (paramIndex, decorator) {
30
- return function (target, key) {
31
- decorator(target, key, paramIndex);
32
- };
33
- };
34
- Object.defineProperty(exports, '__esModule', { value: true });
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
35
15
  exports.ThrottlerGuard = void 0;
36
- const common_1 = require('@nestjs/common');
37
- const core_1 = require('@nestjs/core');
38
- const md5 = require('md5');
39
- const throttler_storage_interface_1 = require('./throttler-storage.interface');
40
- const throttler_constants_1 = require('./throttler.constants');
41
- const throttler_decorator_1 = require('./throttler.decorator');
42
- const throttler_exception_1 = require('./throttler.exception');
16
+ const common_1 = require("@nestjs/common");
17
+ const core_1 = require("@nestjs/core");
18
+ const md5 = require("md5");
19
+ const throttler_storage_interface_1 = require("./throttler-storage.interface");
20
+ const throttler_constants_1 = require("./throttler.constants");
21
+ const throttler_decorator_1 = require("./throttler.decorator");
22
+ const throttler_exception_1 = require("./throttler.exception");
43
23
  let ThrottlerGuard = class ThrottlerGuard {
44
- constructor(options, storageService, reflector) {
45
- this.options = options;
46
- this.storageService = storageService;
47
- this.reflector = reflector;
48
- this.headerPrefix = 'X-RateLimit';
49
- this.errorMessage = throttler_exception_1.throttlerMessage;
50
- }
51
- async canActivate(context) {
52
- const handler = context.getHandler();
53
- const classRef = context.getClass();
54
- if (
55
- this.reflector.getAllAndOverride(throttler_constants_1.THROTTLER_SKIP, [handler, classRef])
56
- ) {
57
- return true;
24
+ constructor(options, storageService, reflector) {
25
+ this.options = options;
26
+ this.storageService = storageService;
27
+ this.reflector = reflector;
28
+ this.headerPrefix = 'X-RateLimit';
29
+ this.errorMessage = throttler_exception_1.throttlerMessage;
30
+ }
31
+ async canActivate(context) {
32
+ const handler = context.getHandler();
33
+ const classRef = context.getClass();
34
+ if (this.reflector.getAllAndOverride(throttler_constants_1.THROTTLER_SKIP, [handler, classRef])) {
35
+ return true;
36
+ }
37
+ const routeOrClassLimit = this.reflector.getAllAndOverride(throttler_constants_1.THROTTLER_LIMIT, [
38
+ handler,
39
+ classRef,
40
+ ]);
41
+ const routeOrClassTtl = this.reflector.getAllAndOverride(throttler_constants_1.THROTTLER_TTL, [
42
+ handler,
43
+ classRef,
44
+ ]);
45
+ const limit = routeOrClassLimit || this.options.limit;
46
+ const ttl = routeOrClassTtl || this.options.ttl;
47
+ return this.handleRequest(context, limit, ttl);
58
48
  }
59
- const routeOrClassLimit = this.reflector.getAllAndOverride(
60
- throttler_constants_1.THROTTLER_LIMIT,
61
- [handler, classRef],
62
- );
63
- const routeOrClassTtl = this.reflector.getAllAndOverride(throttler_constants_1.THROTTLER_TTL, [
64
- handler,
65
- classRef,
66
- ]);
67
- const limit = routeOrClassLimit || this.options.limit;
68
- const ttl = routeOrClassTtl || this.options.ttl;
69
- return this.handleRequest(context, limit, ttl);
70
- }
71
- async handleRequest(context, limit, ttl) {
72
- const { req, res } = this.getRequestResponse(context);
73
- if (Array.isArray(this.options.ignoreUserAgents)) {
74
- for (const pattern of this.options.ignoreUserAgents) {
75
- if (pattern.test(req.headers['user-agent'])) {
76
- return true;
49
+ async handleRequest(context, limit, ttl) {
50
+ const { req, res } = this.getRequestResponse(context);
51
+ if (Array.isArray(this.options.ignoreUserAgents)) {
52
+ for (const pattern of this.options.ignoreUserAgents) {
53
+ if (pattern.test(req.headers['user-agent'])) {
54
+ return true;
55
+ }
56
+ }
77
57
  }
78
- }
58
+ const tracker = this.getTracker(req);
59
+ const key = this.generateKey(context, tracker);
60
+ const ttls = await this.storageService.getRecord(key);
61
+ const nearestExpiryTime = ttls.length > 0 ? Math.ceil((ttls[0] - Date.now()) / 1000) : 0;
62
+ if (ttls.length >= limit) {
63
+ res.header('Retry-After', nearestExpiryTime);
64
+ this.throwThrottlingException(context);
65
+ }
66
+ res.header(`${this.headerPrefix}-Limit`, limit);
67
+ res.header(`${this.headerPrefix}-Remaining`, Math.max(0, limit - (ttls.length + 1)));
68
+ res.header(`${this.headerPrefix}-Reset`, nearestExpiryTime);
69
+ await this.storageService.addRecord(key, ttl);
70
+ return true;
71
+ }
72
+ getTracker(req) {
73
+ return req.ip;
74
+ }
75
+ getRequestResponse(context) {
76
+ const http = context.switchToHttp();
77
+ return { req: http.getRequest(), res: http.getResponse() };
78
+ }
79
+ generateKey(context, suffix) {
80
+ const prefix = `${context.getClass().name}-${context.getHandler().name}`;
81
+ return md5(`${prefix}-${suffix}`);
79
82
  }
80
- const tracker = this.getTracker(req);
81
- const key = this.generateKey(context, tracker);
82
- const ttls = await this.storageService.getRecord(key);
83
- const nearestExpiryTime = ttls.length > 0 ? Math.ceil((ttls[0] - Date.now()) / 1000) : 0;
84
- if (ttls.length >= limit) {
85
- res.header('Retry-After', nearestExpiryTime);
86
- this.throwThrottlingException(context);
83
+ throwThrottlingException(context) {
84
+ throw new throttler_exception_1.ThrottlerException(this.errorMessage);
87
85
  }
88
- res.header(`${this.headerPrefix}-Limit`, limit);
89
- res.header(`${this.headerPrefix}-Remaining`, Math.max(0, limit - (ttls.length + 1)));
90
- res.header(`${this.headerPrefix}-Reset`, nearestExpiryTime);
91
- await this.storageService.addRecord(key, ttl);
92
- return true;
93
- }
94
- getTracker(req) {
95
- return req.ip;
96
- }
97
- getRequestResponse(context) {
98
- const http = context.switchToHttp();
99
- return { req: http.getRequest(), res: http.getResponse() };
100
- }
101
- generateKey(context, suffix) {
102
- const prefix = `${context.getClass().name}-${context.getHandler().name}`;
103
- return md5(`${prefix}-${suffix}`);
104
- }
105
- throwThrottlingException(context) {
106
- throw new throttler_exception_1.ThrottlerException(this.errorMessage);
107
- }
108
86
  };
109
- ThrottlerGuard = __decorate(
110
- [
111
- common_1.Injectable(),
112
- __param(0, throttler_decorator_1.InjectThrottlerOptions()),
113
- __param(1, throttler_decorator_1.InjectThrottlerStorage()),
114
- __metadata('design:paramtypes', [Object, Object, core_1.Reflector]),
115
- ],
116
- ThrottlerGuard,
117
- );
87
+ ThrottlerGuard = __decorate([
88
+ (0, common_1.Injectable)(),
89
+ __param(0, (0, throttler_decorator_1.InjectThrottlerOptions)()),
90
+ __param(1, (0, throttler_decorator_1.InjectThrottlerStorage)()),
91
+ __metadata("design:paramtypes", [Object, Object, core_1.Reflector])
92
+ ], ThrottlerGuard);
118
93
  exports.ThrottlerGuard = ThrottlerGuard;
119
- //# sourceMappingURL=throttler.guard.js.map
94
+ //# sourceMappingURL=throttler.guard.js.map