Skip to content

Commit 20b5c99

Browse files
committed
feat: implement throttle configuration and usage for rate limiting
1 parent 0db3b64 commit 20b5c99

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Throttle } from '@nestjs/throttler';
2+
3+
import { ThrottleConfigs, UseThrottle, configs } from './index';
4+
5+
jest.mock('@nestjs/throttler', () => ({
6+
Throttle: jest.fn(),
7+
}));
8+
9+
describe('UseThrottle', () => {
10+
it('should return a Throttle instance with the correct config', () => {
11+
const name: ThrottleConfigs = 'medium';
12+
const config = configs[name];
13+
14+
UseThrottle(name);
15+
16+
expect(Throttle).toHaveBeenCalledWith({
17+
default: config,
18+
});
19+
});
20+
});
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import {
2+
Resolvable,
3+
Throttle,
4+
ThrottlerGenerateKeyFunction,
5+
ThrottlerGetTrackerFunction,
6+
} from '@nestjs/throttler';
7+
interface ThrottlerMethodOrControllerOptions {
8+
limit?: Resolvable<number>;
9+
ttl?: Resolvable<number>;
10+
blockDuration?: Resolvable<number>;
11+
getTracker?: ThrottlerGetTrackerFunction;
12+
generateKey?: ThrottlerGenerateKeyFunction;
13+
}
14+
15+
export type ThrottleConfigs =
16+
| 'short'
17+
| 'medium'
18+
| 'long'
19+
| 'very-long'
20+
| 'super-long';
21+
22+
export const configs: {
23+
[key in ThrottleConfigs]: ThrottlerMethodOrControllerOptions;
24+
} = {
25+
short: {
26+
ttl: 1000, // 1 second
27+
limit: 5,
28+
},
29+
medium: {
30+
ttl: 60 * 1000, // 1 minute
31+
limit: 100,
32+
},
33+
long: {
34+
ttl: 60 * 60 * 100, // 1 hour
35+
limit: 1000,
36+
},
37+
// one every 15 minutes
38+
'very-long': {
39+
ttl: 15 * 60 * 1000,
40+
limit: 1,
41+
},
42+
// one every 1 hour
43+
'super-long': {
44+
ttl: 60 * 60 * 1000,
45+
limit: 1,
46+
},
47+
};
48+
49+
/**
50+
* Applies a throttle configuration based on the provided name.
51+
*
52+
* @param {ThrottleConfigs} name - The name of the throttle configuration to use.
53+
* @returns {Throttle} - The throttle instance configured with the specified settings.
54+
* @example
55+
* ```ts
56+
* @UseThrottle('super-long')
57+
* @Post('login/magic-link')
58+
* public async magicLinkLogin(@Req() req: Request, @Res() res: Response) {
59+
* return this.magicLinkEmailStrategy.send(req, res);
60+
* }
61+
*/
62+
export const UseThrottle = (name: ThrottleConfigs) => {
63+
const config = configs[name];
64+
return Throttle({
65+
default: config,
66+
});
67+
};

0 commit comments

Comments
 (0)