Skip to main content
TypeOrm offers the possibility to connect your application to multiple databases or schemas. More details on this can be found on their official documentation. Further, the official @nestjs/typeorm package also provides functionality to support multiple databases within the application. For details, consider the official documentation. Therefore, @ptc-org/nestjs-query-typeorm also offers this functionality. This section will walk you through a short example indicating how to connect your application to multiple databases. Further, this will assume, that you already have a working application with a configured database. Please note that only key aspects are shown here:

Defining multiple connections

First lets set up a constants file to hold our connection names.
constants.ts
Then setup multiple database connections.
app.module.ts
Of course, there can only be one default database connection. All other connections must have a proper name set up. Further, this name must be used when connecting against this specific entity.

Create a new Feature Module

Second, you need to create a new module for the feature that should store its data in another database using the previously defined connection. First, define your Entity class that is stored within the database
secret/secret.entity.ts
and the corresponding ObjectType that is used for GraphQL
secret/secret.dto.ts
Now lets register the SecretEntity with NestjsQueryTypeOrmModule. The only difference is you need to pass the name of the Connection when importing respective TypeOrmModule.
secret/secret.module.ts
Now the NestjsQueryGraphQLModule will create a Resolver for the SecretDTO and SecretEntity that will use the custom connection.

Custom TypeOrmQueryService

If you want to create a custom SecretService responsible for the database access, a custom QueryService, you need to pass an additional argument to the @InjectRepository() decorator that indicates the Connection you are using. This string has to match the name property in the TypeOrmModule options!
secret/secret.service.ts
For the sake of brevity, the AssemblerService is not covered here, as it should not directly interact with the database itself. Therefore, no further adaptations are required. This also applies to the Resolver! For a full example see the examples.