Injectable EventSubscribers
See original GitHub issueIs your feature request related to a problem? Please describe. It would be awesome if EventSubscriber classes could support NestJs DI so we can inject dependencies in them.
Describe the solution you’d like
The current @Subscriber()
decorator cannot be used as it directly creates a new instance:
https://github.com/mikro-orm/mikro-orm/blob/master/packages/core/src/decorators/Subscriber.ts#L8
And I didn’t find a clear solution to remove the attached subscriber before MikroORM init.
I think the easiest way is to have a new decorator (could be @InjectableSubscriber()
, that also wraps Nestjs @Injectable()
?) that simply adds a metadata to the class prototype flagging it as a Subscriber
, then the class has to be registered as a provider
inside a Module (like any nestjs providers).
Then follow a common Nestjs pattern, “disover” this providers via the custom metadata and do stuff with them, in our case
register them as subscriber (em.getEventManager().registerSubscriber()
).
Additional context
As a reference, @nestjs/bull
does the same for registering queue processors https://github.com/nestjs/bull/blob/master/lib/bull.explorer.ts .
It is a bit more complicated since it has to check every class methods instead of just the class, what we need are just the first lines of explore()
:
const providers: InstanceWrapper[] = this.discoveryService
.getProviders()
.filter((wrapper: InstanceWrapper) =>
this.metadataAccessor.isQueueComponent(wrapper.metatype),
);
Replace isQueueComponent
with something like isSubscriberComponent
and voilà, we have an array of all provided subscribers.
Issue Analytics
- State:
- Created 3 years ago
- Comments:9 (4 by maintainers)
This is already possible:
Can you also put this to documents? I was looking for this solution for hours.