我想为我的模块添加版本,但我不知道我该怎么做。我试图创建一个通用的module.ts,但同样的服务名称杀死了我们每个人。我尝试了不同的module.ts版本,它更好,但具有相同名称的服务不起作用。
这是我的最后一个结构:test-module
1.0
controllers
test.controller.ts
services
test.service.ts
test.module.ts
1.1
controllers
test.controller.ts
services
test.service.ts
test.module.ts
这是我对这些版本的测试服务:
import * as _ from 'lodash';
import { Injectable } from '@nestjs/common';
@Injectable()
export class TestService {
public test() {
return '1.0'; // and 1.1 in 1.1 directory
}
}
这是我的module.ts:
import { Module, Logger } from '@nestjs/common';
import { TestModule as DorotTwo } from 'test-module/1.1/test.module';
import { TestModule as DorotOne } from 'test-module/1.0/test.module'
@Module({
controllers: [ProtobufController],
providers: [],
imports: [
DorotTwo,
DorotOne,
],
})
export class ProjectModule {
constructor() {
Logger.log('App initialized');
}
}
这是项目中想要使用模块的简单测试控制器。尝试从1.0或1.1导入TestService但测试函数的响应始终为1.0,因为这是导入中的最后一个元素。
@Controller()
export class ProtobufController {
constructor(private readonly testService: TestService) {
console.log(this.testService.test()); // Always 1.0
}
.....
如果我为服务使用完全不同的名称(例如:UserAuthenticationService10,RegisterAuthenticationService10),它会工作,但这很糟糕,如果我忘了在新版本中重命名它,它将覆盖。
是否存在一个示例,我可以阅读如何创建此版本化模块?
使用自定义提供商会是一个令人满意的解决方案吗?
例:
// 1.0
@Module({
providers: [
{ provide: 'TestService_1.0', useClass: TestService }
]
})
export class TestModule {}
// 1.1
@Module({
providers: [
{ provide: 'TestService_1.1', useClass: TestService }
]
})
export class TestModule {}
// Then
@Controller()
export class ProtobufController {
constructor(
@Inject('TestService_1.0') private readonly testService_10,
@Inject('TestService_1.1') private readonly testService_11
) {
console.log(this.testService_10.test());
console.log(this.testService_11.test());
}
}
我显然没有测试过这个,你应该根据你的用例进行调整。我建议你看看https://docs.nestjs.com/fundamentals/custom-providers。