typeorm - understand provider scope and connection pooling

Viewed 69

Does typeorm have a way to cache/store connection for a tenant/schema so that we can use the cached database connection per schema/tenant?

This document describes of a method to inject the connection in the constructor of the service to get the repository:

constructor(
    @Inject(CONNECTION) connection: Connection,
  ) {
    this.catsRepository = connection.getRepository(Cat);
  }

But, it also mentions the following paragraph:

The CONNECTION is a provider created within a factory that consumes the tenantId set up by the middleware, and returns the connection if relevant. Note that this provider is scoped on REQUEST, which means that all downstream consumers of CONNECTION will also be request-scoped by default. This has unfortunate performance implications (e.g., CatsService has to be destroyed and recreated for each request, whereas TenantsService can be reused across requests), but it is required so that no mess-up occurs across tenants. A way around this is to remove repository setup from the constructor and perform it at the start of each function (much more verbose).

so , it basically seems to create a new connection even though the request is from the same tenant. I thought the purpose of connection pool was to store connections for persistence, but it doesn't appear so .

Notice the line:

A way around this is to remove repository setup from the constructor and perform it at the start of each function (much more verbose).

I have two questions:

  • How to cache/store connections for typeorm to deal with multitenancy to process each request according to the tenant/schema.
  • A way around this is to remove repository setup from the constructor and perform it at the start of each function (much more verbose).
    how is this supposed to be implemented, a brief explanation would suffice, but some code would be really helpful.

Thanks in advance.

0 Answers
Related