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

feat: pass context to get tracker fn as second arg #2177

Merged
merged 2 commits into from
Dec 10, 2024

Conversation

manuchekhr32
Copy link
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

I tried to make "dynamic" tracking with nestjs metadata for multiple scenarios. For example by default I want tracker to be req.ip value, but in some cases I want it to get the value from req.body.username. For a temporary solution I find that creating individual guards for each scenario, but if I have access to ExecutionContext I can get "key" from the metadata. Something like this:

// throttler-proxy.guard.ts
protected async getTracker(req: Record<string, any>, context: ExecutionContext): Promise<string> {
    const key = this.reflector.get(ThrottlerTracker, context.getHandler())
    const tracker = req?.[key] ?? req.ip
    return tracker
}

// throttler-tracker.decorator.ts
export const ThrottlerTracker = Reflector.createDecorator<string>();

// auth.controller.ts
@Post('login')
@ThrottlerTracker('body.username')
login () { ... }

Issue Number: N/A

What is the new behavior?

Passes ExecutionContext to getTracker method as second argument. First time contributing to be honest, I hesitated to replace first param req to context.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

As I said it's my first time contributing hope you understand. Also not sure if it's a breaking change

@jmcdo29
Copy link
Member

jmcdo29 commented Dec 3, 2024

This looks like it could be useful, and a pretty simple change. Would you mind making a changeset via pnpm changeset and following the wizard for a minor change?

@manuchekhr32
Copy link
Contributor Author

This looks like it could be useful, and a pretty simple change. Would you mind making a changeset via pnpm changeset and following the wizard for a minor change?

done ✅

@jmcdo29 jmcdo29 merged commit fc93f3a into nestjs:master Dec 10, 2024
3 checks passed
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

Successfully merging this pull request may close these issues.

2 participants