mikro-orm-examples
mikro-orm-examples copied to clipboard
Add example for Multi-Tenant
Is your feature request related to a problem? Please describe. Using multiple connections and binding connections to entities.
Describe the solution you'd like For example: A request is sent to an API and a middleware would introspect and select which tenant database connection.
I see that the .init
the function would preload all the entities. Would that cause any problem to somehow load the entities on-demand based on different database connections?
Ex:
GET /foo (123)
- load database connection for tenant 123.
- When using entities, they would be associated with client 123 connection during the request.
I've found in the docs that it's possible to solve that by using const em = orm.em.fork();
or
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
For ref, I think having something like https://vincit.github.io/objection.js/recipes/multitenancy-using-multiple-databases.html in the docs would be very beneficial.
A request is sent to an API and a middleware would introspect and select which tenant database connection.
So you would have a list of defined tenants in the config somewhere, available to the middleware?
I see that the .init the function would preload all the entities. Would that cause any problem to somehow load the entities on-demand based on different database connections?
Not sure what you mean by "preload all entities". You can pass a list of entities to analyse/discover. All entities you want to use need to be discovered (and they all need to be valid, e.g. if you have Book entity that is referring to Author entity, you need to discover both).
I've found in the docs that it's possible to solve that by using const em = orm.em.fork(); or
Forking/request context helper are needed, that is not just about multi tenancy, you need to have a clear context (fork) for each request.
I never used it this way (never worked with a tenant per db app), so its hard to give you advice on how to do it the right way :] But what they do in objection should be possible, you can augment the req
object with the right instance of EM. But to have multiple dbs, you need to have multiple instances of the ORM, that is not about EM forking.
With a tenant per schema (all in one db) you could use single ORM instance I guess.
@B4nan I was just looking into this for a future project. I've done multi-tenant in the past using a Document Store... it was fairly easy to implement.
you can augment the req object with the right instance of EM. But to have multiple dbs, you need to have multiple instances of the ORM
This is probably not the best option given the overhead of 1000 tenents I imagine. I think the best approach is to be able to tell the ORM which database to point to on a given request. Any ideas if that's doable?