(Transaction?) Events not triggering subscriber when using forked EM with fresh event manager #231
-
|
Describe the bug To that end, I am adding a subscriber that I instantiate on a per-request basis. This subscriber needs access to the express request to do its thing, so when I am passing the request to it. I also want to clean-up the subscriber so that these events only trigger for this request. So, I forked the EM and gave it a fresh event manager (so that the subscriber gets cleaned-up). When I do this, my subscriber does not trigger at all, even though I am using the forked EM to persist and flush. Interestingly even, if I do not provide a fresh event manager, the subscriber triggers, but instead the listener methods get triggered 2 times. I have tried not forking the entity manager (does't the Mikro-orm middleware already give use request scoped entity managers?). The subscriber methods trigger, but new subscribers keep getting added every time a request comes in (I did not except this as I expected to get a fresh EM every request). I also think that the subscriber might trigger more times than excepted (instead of being called 1, the methods get called 2 times when not having a fresh event manager). Stack trace To Reproduce
Expected behavior Additional context Versions
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
|
It might also be the case that I am wrong about how the Entity manager and/or events are supposed to work. Maybe I need a different approach to achieve what I want (doing some prep work immediately after a transaction runs, and some cleanup work after a transaction ends)? Also, I tried reproducing the issue with NestJS (so purely in Mikro-orm + Postgres). I could not reproduce the issue there. So I am guessing there must be something wrong with how the NestJS integration is set up. |
Beta Was this translation helpful? Give feedback.
-
|
Your problem is most likely the fact that you keep the This is for context resolution with the RequestContext helper via middlewares, with global services in the DI container - the opposite of what you are trying to do with the nestjs request scopes. Try removing that option. |
Beta Was this translation helpful? Give feedback.
Note that you still have the RequestContext middlewares set up, it's the default behaviour of the nest orm adapter (see https://github.com/mikro-orm/nestjs/blob/master/src/mikro-orm-core.module.ts#L262-L264), and you are not disabling that in the
forRootcall. That would be another way to fix this (you should do it regardless if you want to use nest request scopes - which I would btw discourage, they will have perf penalty, bigger than the ALS used forRequestContextmiddleware, and you don't need those here, you can use ALS to keep a reference to the request object too).