|
| 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