I'm currently using nestjs to create a straightforward HTTP rest API, utilizing typeorm. I have set up 2 Postgres databases and would like the ability to access both, although not necessarily simultaneously.
Essentially, I am looking to designate which database an endpoint should utilize, preferably through a decorator such as SetMetadata
.
Below is an example of my controller:
@Get('/posts')
@SetMetadata('DB_HOST', 'localhost')
async getPosts(): Promise<Posts> {
return this.postService.getPosts()
}
This is how my module appears:
Module({
controllers: [
AppController,
],
exports: [ConfigModule],
imports: [
ConfigModule,
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
/* Unable to locate this token */
inject: [ConfigService, Reflector, ExecutionContext],
useFactory: async (config: ConfigService, reflector: Reflector, executionContext: ExecutionContext) => {
return {
...config.getPostgresConfig(),
entities,
synchronize: true,
type: "postgres",
host: reflector.getAllAndOverride('DB_HOST', [executionContext.getHandler(), executionContext.getClass()])
} as PostgresConnectionOptions;
},
}),
],
providers: [AppService],
})
export class AppModule {}
I am facing challenges with retrieving the execution context outside of a guard or interceptor.
Is there a workaround for this?
If not, are there alternative methods to marking an endpoint and extracting the value in a provider?