Search code examples
mikro-orm

Are custom repository instances created per request?


I am trying to create an application with mikro-orm and apollo-server-express, I want to use the batch processing and the caching of the Facebook dataloader.

Normally, Facebook dataloader instances are creates per request. If mikro-orm also creates custom repository instances per request and if all calls to EntityManager.getRepository() in the same request gets the same instance, it may be the perfect place to create the dataloader instances.


Solution

  • Repositories are created as singletons, so only one instance exists per EntityManager instance. You should fork this EM to have one instance per request, either manually, or via RequestContext middleware:

    https://b4nan.github.io/mikro-orm/identity-map/

    This way, each request will have its own EntityManager, that will have its own cache of repository instances.

    Keep in mind that if you use RequestContext, you should get the request specific EntityManager from it, and get the repository from there:

    // beware that this will return null if the context is not yet started
    const em = RequestContext.getEntityManager();
    
    // gets request specific repository instance
    const repo = em.getRepository(Book);