Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Share same context between 'limit' and 'ttl' #1576

Open
1 task done
siisee11 opened this issue Jul 12, 2023 · 4 comments
Open
1 task done

Share same context between 'limit' and 'ttl' #1576

siisee11 opened this issue Jul 12, 2023 · 4 comments

Comments

@siisee11
Copy link

Is there an existing issue that is already proposing this?

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

.
@jmcdo29
Copy link
Member

jmcdo29 commented Jul 12, 2023

So I see two options here:

  1. leave this to the developer to create a memoization function for it (not hard to create, but possibly not the best DX)
  2. Create a getContext or contextResolver method on the throttler's options and leave the memoization to the package (more maintenance for package maintainers, but smoother DX)

I'm leaning towards the optional contextResolver as I think that would lead to the best DX, the only concern I have is what if the contexts should be different for some reason, and how do we type this out properly. I'll keep thinking on these and work on it as I can

@siisee11
Copy link
Author

Option 2 looks nice. I hope you find a proper way to implement it!

And I have another question. I applied JWTGaurd globally and It put the user to ExecutionContext and then I can get the user as a param in the controller. Can I do something similar in throttler module?

  @Post(":id/run")
  async run(
    @Param("id") id: string,
    @Req() req: Request,
    @GetUser() user: User,
    @Body() body: RunAppDto,
    @Res() response: Response
  ) {

GetUser

export const GetUser = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user;

    return data ? user?.[data] : user;
  }
);

@siisee11 siisee11 reopened this Jul 13, 2023
@jmcdo29
Copy link
Member

jmcdo29 commented Jul 13, 2023

That would entirely depend on when the req.user gets populated. Usually this is done by the AuthGuard() unless you have a custom solution, and most people would have that bound after the ThrottlerGuard, so it wouldn't (immediately) be possible. You could set up the same paring logic though. It all just really depends

@siisee11
Copy link
Author

Thank you:) Is there a way to change the order of Guard invocation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants