NestJS lazy loading a module importing TypeORM doesn't register "Connection" providers
I faced the same problem, unfortunately. I've got it working via the ASYNC_CONNECTION
provider:
import { ConnectionOptions, createConnection, getConnection } from 'typeorm';
providers: [{
provide: 'ASYNC_CONNECTION',
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const { host, port, username, password, database } = configService.get('db');
const connection: ConnectionOptions = {
type: 'postgres',
host,
port,
username,
password,
database,
name: 'custom',
entities: [...entities],
synchronize: false,
namingStrategy: new SnakeNamingStrategy(),
};
try {
getConnection(connection.name);
} catch (error) {
return await createConnection(connection);
}
}
}]
Then you can inject the ASYNC_CONNECTION
provider wherever you want:
@Inject('ASYNC_CONNECTION')
private connection: Connection,
And use the classic repository approach with the entities you've declared above:
this.connection.getRepository(<Entity>).findOne({})
That's it.