NestJS延迟加载导入TypeORM的模块没有't注册"连接"提供者



我有一个DatabaseModule,它导入TypeORM并启动db连接(参见database.module.ts)。我在crud模块上使用该模块,当以经典方式注册模块时,一切都工作正常。

但是当我延迟加载相同的模块时,它中断了,我得到了"无法解决连接";错误。

"ERROR [exceptionhandler] Nest无法解析productrerepository(?)的依赖关系。请确保索引[0]处的参数Connection在TypeOrmModule上下文中可用。">

(我正在编写无服务器的函数,因此尝试延迟加载。)

// product.module.ts: the module I lazy-load
@Module({
imports: [
DatabaseModule.register({
entities: [Product],
}),
],
// database.module.ts: the module that creates the db connections
export interface DatabaseOptions {
entities: any[];
}
@Module({})
export class DatabaseModule {
static register(options: DatabaseOptions): DynamicModule {
return {
module: DatabaseModule,
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: '0.0.0.0',
port: 3306,
username: 'root',
password: '****',
database: 'example',
retryAttempts: 5,
synchronize: true,
entities: options.entities,
}),
TypeOrmModule.forFeature(options.entities),
],
providers: [],
exports: [TypeOrmModule],
};
}
}

这是延迟加载部分。

// app.controller.ts
@Get()
async createProduct(): Promise<Product> {
// Lazy load the module that imports the DatabaseModule to lazy-load the connections.
const { ProductModule } = await import('./product/product.module');
const productModule = await this.lazyModuleLoader.load(() => ProductModule);
const { ProductService } = await import('./product/product.service');
// It breaks here, 'Connection' providers are not registered.
const productService = productModule.get(ProductService);
return productService.create();
}

再次,当我在主AppModule中注册ProductModule时,它工作正常,所以我希望模块以与惰性加载相同的方式工作。.

我想我必须懒惰加载更多的东西,这工作,但我不明白为什么连接/存储库提供程序不可用,当我懒惰加载产品模块…😦

生殖回购(有一个docker-compose与mysql镜像本地调试)。

不幸的是,我也遇到了同样的问题。我已经通过ASYNC_CONNECTION提供程序使其工作:

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);
}
}
}]

然后你可以在任何你想要的地方注入ASYNC_CONNECTION提供者:

@Inject('ASYNC_CONNECTION')
private connection: Connection,

并使用经典的存储库方法来处理您在上面声明的实体:

this.connection.getRepository(<Entity>).findOne({})

最新更新