throttler
throttler copied to clipboard
Share same context between 'limit' and 'ttl'
Is there an existing issue that is already proposing this?
- [X] I have searched the existing issues
Is your feature request related to a problem? Please describe it
Below is my throttler module code. I used identical code for both the "ttl" and "limit" functions, resulting in fetching the same data from the database twice. Is there a way to share the ExecutionContext between the "limit" and "ttl" functions to avoid this duplication?
ThrottlerModule.forRootAsync({
imports: [ConfigModule, JwtModule, GlobalModule],
inject: [ConfigService, JwtService, SupabaseService],
useFactory: (
config: ConfigService,
jwtService: JwtService,
supabaseService: SupabaseService
) => ({
ttl: async (context) => {
const request = context.switchToHttp().getRequest();
const extractor = ExtractJwt.fromAuthHeaderAsBearerToken();
const accessToken = ExtractJwt.fromExtractors([extractor])(request);
const payload = jwtService.decode(accessToken);
const userId = payload.sub;
const expressPass = await supabaseService.getExpressPass(userId);
return expressPass ? 1000 : 60;
},
limit: async (context) => {
const request = context.switchToHttp().getRequest();
const extractor = ExtractJwt.fromAuthHeaderAsBearerToken();
const accessToken = ExtractJwt.fromExtractors([extractor])(request);
const payload = jwtService.decode(accessToken);
const userId = payload.sub;
const expressPass = await supabaseService.getExpressPass(userId);
return expressPass ? 1000 : 1;
},
storage: config.get("REDIS_URL")
? new ThrottlerStorageRedisService(config.get("REDIS_URL"))
: undefined,
}),
}),
```
### Describe the solution you'd like
Inject data to request before executing ttl, limit function.
const expressPass = request.expressPass
### Teachability, documentation, adoption, migration strategy
_No response_
### What is the motivation / use case for changing the behavior?
.