nest icon indicating copy to clipboard operation
nest copied to clipboard

feat(microservices): add event typings to the `@EventPattern` decorator

Open joelday opened this issue 7 months ago • 2 comments

Adds overloads for @EventPattern to allow validation that decorated method signatures match event payload types based on a specified mapping type. Includes tests demonstrating correct usage and error cases with // @ts-expect-error.

PR Checklist

Please check if your PR fulfills the following requirements:

  • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
  • [x] Tests for the changes have been added (for bug fixes / features)
  • [ ] Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • [ ] Bugfix
  • [x] 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?

Issue Number: N/A

What is the new behavior?

Adds overloads to the @EventPattern decorator that creates a static type constraint between the pattern and the decorated method's parameter type.

Example:

type FooMessage = {
  foo: string;
};

type BarMessage = {
  bar: number;
};

type EventTypes = {
  'event-pattern-foo': FooMessage;
  'event-pattern-bar': BarMessage;
};

class FooBarTestComponent {
  // correct
  @EventPattern<EventTypes>('event-pattern-bar')
  testBar(event: BarMessage) {}

  // incorrect (foo is specified, but the parameter type is `string` instead of `FooMessage`
  @EventPattern<EventTypes>('event-pattern-foo')
  testFoo(event: string) {}
}

Does this PR introduce a breaking change?

  • [ ] Yes
  • [x] No

Other information

  • I'm unsure of what documentation should be added/where that lives.
  • I'm unsure of whether or not topic is an appropriate name for these overloads instead of metadata.

joelday avatar Mar 18 '25 17:03 joelday