适用于模块的NestJs版本

时间:2019-04-30 11:06:08

标签: module version nestjs

我想为模块添加版本,但是我不知道该怎么做。我试图创建一个通用的module.ts,但是相同的服务名称杀死了我们每个人。我为版本尝试了不同的module.ts,虽然更好,但是同名的服务无法正常工作。

这是我的最后一个结构: 测试模块

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导入import TestService,但是测试函数的响应始终为1.0,因为这是导入中的最后一个元素。

@Controller()
export class ProtobufController {
  constructor(private readonly testService: TestService) {
    console.log(this.testService.test()); // Always 1.0
  }
.....

例如,如果我对服务使用完全不同的名称(例如:UserAuthenticationService10,RegisterAuthenticationService10),则可以正常工作,但是这太可怕了,如果我忘记以新版本重命名,它将被覆盖。

是否存在一个示例,其中我可以阅读如何创建此版本控制的模块?

1 个答案:

答案 0 :(得分:0)

使用自定义提供程序对您来说是令人满意的解决方案吗?

示例:

// 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