【发布时间】:2020-03-11 02:38:35
【问题描述】:
我正在开发一个链接缩短器,对于我的后端,我有一个 CRUD REST API 来处理身份验证和创建缩短的链接等,我还想处理缩短的 URL 的重定向,但我不希望它们有与我的 API 端点(例如 /api/v1/)相同的路径,因为我使用 setGlobalPrefix 作为我的 API。在网上做了一些研究后,我发现了以下Github issue,它为我的问题提供了解决方案:
async function bootstrap() {
const server = new ExpressAdapter();
const apiFactory = new NestFactoryStatic();
const apiApp = await apiFactory.create(ApiModule, server);
apiApp.setGlobalPrefix('api/v1');
await apiApp.init();
const redirectFactory = new NestFactoryStatic();
const redirectApp = await redirectFactory.create(RedirectModule, server);
await redirectApp.init();
http
.createServer(server.getInstance())
.listen(process.env.PORT || 3000);
}
bootstrap();
但我遇到了另一个问题,我需要访问我的 RedirectModule 中的数据库,我已经为我的 REST API 制作了一个 LinkRepository,但我无法将它导入到 RedirectModule,这里是ApiModule 的代码以及我已经尝试过的代码。
@Module({
imports: [TypeOrmModule.forRoot(typeOrmConfig), LinksModule, AuthModule],
controllers: [LinksController],
providers: [],
})
export class ApiModule {}
RedirectModule 只是尝试将LinkRepository 作为这样的功能导入:
@Module({
imports: [TypeOrmModule.forFeature([LinkRepository])],
controllers: [RedirectController]
})
export class RedirectModule {}
我收到以下错误:
Nest can't resolve dependencies of the LinkRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.
Potential solutions:
- If Connection is a provider, is it part of the current TypeOrmModule?
- If Connection is exported from a separate @Module, is that module imported within TypeOrmModule?
@Module({
imports: [ /* the Module containing Connection */ ]
})
所以我尝试将ApiModule 导入RedirectModule,并在单独的文件中导出TypeOrmModule.forRoot(typeOrmConfig) 并将其导入两个模块,但随后我收到一个错误,告诉我连接已经存在:AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
那么,如何在两个单独的模块之间共享连接?查看Nest's documentation 没有帮助,因为它假定所有模块都是一个大根模块的一部分,这不是我想要做的。
编辑:所以看起来主要问题是跨应用程序共享模块,因为我正在创建具有不同工厂的 2 个应用程序,它会尝试再次重新连接到数据库,因为看起来模块是单例仅在同一个应用程序中。有什么解决办法吗?或者,另一种方式来实现我想要做的事情? (特定模块的不同 URL 前缀)
【问题讨论】:
-
你找到解决办法了吗?
-
解决方案是不使用
NestFactoryStatic,因为它是一个内部API -
如果可能的话,你能发表一个答案吗?我不认为我在使用
NestFactoryStating
标签: node.js typescript nestjs typeorm