mikro-ormbullmq

Does MikroORM require a RequestContext when used with background workers like BullMQ?


I'm using MikroORM with BullMQ workers. When MikroORM is used with Express apps, it requires a RequestContext in order to maintain unique identity maps for each request. I suspect the same is required when processing multiple jobs with the same BullMQ worker.

Has anyone else successfully combined these two libraries? Is it possible to automatically fork the Entity Manager when a worker starts a new job?


Solution

  • You can use @UseRequestContext() decorator for such cases. It will basically act as if the method would be executed after a middleware that adds the context. Note that to use it, this.orm needs to be the MikroORM instance.

    @Injectable()
    export class MyService {
    
      constructor(private readonly orm: MikroORM) { }
    
      @UseRequestContext()
      async doSomething() {
        // this will be executed in a separate context
      }
    
    }
    

    https://mikro-orm.io/docs/usage-with-nestjs/#request-scoped-handlers-in-queues

    (this part of docs is about nestjs, but it's the very same problem with the same solution)

    Alternatively you could use RequestContext.createAsync() explicitly:

    await RequestContext.createAsync(orm.em, async () => {
      // orm.em here will use the contextual fork created just for this handler
    });