Search code examples
typescripttypeorm

TypeORM: Creating a connection in a parent class and using in a child not working


I have a set of microservices that I'm trying to convert over to TypeORM and am seeing some strange behavior. I have a parent class BaseService that handles creating connections (in order to achieve the multi-tenancy that we need it will manage creating new connections to a Db/Schema combination or serving up an existing connection). The creation of the connection seems to be working fine: just to compare I manually created a connection in the microservice itself and the passed-in connection appears to be identical to the manually-created one. But when calling dbConnection.getCustomRepository(...) using the passed-in connection I get an empty object whereas calling the same thing using the manually-created connection it works just fine. Is there something that I'm not aware of with scoping of the connection management...can you not pass around a connection object like you could with something like knex? Is it actually using the global connection manager even though I'm calling getCustomRepository on the instance of the connection? Thanks for any light you can shed on the issue.

Edit: just for some more code context in case it helps...

This does not work (widgetRepository is empty):

async getWidgets(dbConnection, query): Promise < Widget[] > {
  const widgetRepository: WidgetRepository = dbConnection.getCustomRepository(
    WidgetRepository
  );
  return widgetRepository.getWidgets();
}

This does work:

async getWidgets(dbConnection, query): Promise < Widget[] > {
  const testConnection = await createConnection({
    ...
  }); //inspecting this appears to be identical to dbConnection
  const widgetRepository: WidgetRepository = testConnection.getCustomRepository(
    WidgetRepository
  );
  return widgetRepository.getWidgets();
}

(dbConnection being passed in is being created in exactly the same way as testConnection, just in a parent class that exists in another package)


Solution

  • Ok I think I found the reason this is happening...and a decent solution. The responsible code is here: https://github.com/typeorm/typeorm/blob/master/src/entity-manager/EntityManager.ts#L790 (if (entityRepositoryInstance instanceof Repository) {...}) which I guess was failing because it was checking against a different instance of Repository (since each individual project had to import its own typeorm). The solution that works for me is to just re-export typeorm in my single project (the one that is responsible for creating and managing the connections).