Nestjs依赖注入和DDD /清理架构

Alerosa

我正在尝试通过实现一个干净的架构结构来测试Nestjs,并且想验证我的解决方案,因为我不确定我是否知道执行此操作的最佳方法。请注意,该示例几乎是伪代码,并且缺少许多类型或泛型,因为它们不是讨论的重点。

从域逻辑开始,我可能想在类似于以下类的类中实现它:

@Injectable()
export class ProfileDomainEntity {
  async addAge(profileId: string, age: number): Promise<void> {
    const profile = await this.profilesRepository.getOne(profileId)
    profile.age = age
    await this.profilesRepository.updateOne(profileId, profile)
  }
}

在这里,我需要访问profileRepository,但是遵循干净架构的原理,我现在不想为实现而烦恼,所以我为此写了一个接口:

interface IProfilesRepository {
  getOne (profileId: string): object
  updateOne (profileId: string, profile: object): bool
}

然后,将依赖项注入到ProfileDomainEntity构造函数中,并确保它遵循预期的接口:

export class ProfileDomainEntity {
  constructor(
    private readonly profilesRepository: IProfilesRepository
  ){}

  async addAge(profileId: string, age: number): Promise<void> {
    const profile = await this.profilesRepository.getOne(profileId)
    profile.age = age

    await this.profilesRepository.updateOne(profileId, profile)
  }
}

然后创建一个简单的内存实现,让我运行代码:

class ProfilesRepository implements IProfileRepository {
  private profiles = {}

  getOne(profileId: string) {
    return Promise.resolve(this.profiles[profileId])
  }

  updateOne(profileId: string, profile: object) {
    this.profiles[profileId] = profile
    return Promise.resolve(true)
  }
}

现在是时候使用一个模块将所有内容连接在一起:

@Module({
  providers: [
    ProfileDomainEntity,
    ProfilesRepository
  ]
})
export class ProfilesModule {}

这里的问题是显然ProfileRepository实现了,IProfilesRepository但是没有实现IProfilesRepository,因此,据我了解,令牌是不同的,Nest无法解决依赖关系。

我发现的唯一解决方案是使用自定义提供程序来手动设置令牌:

@Module({
  providers: [
    ProfileDomainEntity,
    {
      provide: 'IProfilesRepository',
      useClass: ProfilesRepository
    }
  ]
})
export class ProfilesModule {}

ProfileDomainEntity通过指定要用于的令牌来修改@Inject

export class ProfileDomainEntity {
  constructor(
    @Inject('IProfilesRepository') private readonly profilesRepository: IProfilesRepository
  ){}
}

这是处理所有依赖项的合理方法还是我完全偏离了轨道?有更好的解决方案吗?我对所有这些东西(NestJs,干净的体系结构/ DDD和Typescript)还比较陌生,所以我在这里可能完全错了。

谢谢

阿曼克

由于语言的限制/功能(请参见结构化类型与标称类型),因此无法通过NestJS中的接口解决依赖性

而且,如果您使用接口定义依赖项(类型),则必须使用字符串标记。但是,您也可以使用类本身,也可以将其名称用作字符串文字,因此在注入依赖类的构造函数期间,无需提及它。

例:

// *** app.module.ts ***
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppServiceMock } from './app.service.mock';

process.env.NODE_ENV = 'test'; // or 'development'

const appServiceProvider = {
  provide: AppService, // or string token 'AppService'
  useClass: process.env.NODE_ENV === 'test' ? AppServiceMock : AppService,
};

@Module({
  imports: [],
  controllers: [AppController],
  providers: [appServiceProvider],
})
export class AppModule {}

// *** app.controller.ts ***
import { Get, Controller } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  root(): string {
    return this.appService.root();
  }
}

您还可以使用抽象类而不是接口,或为接口和实现类赋予相似的名称(并就地使用别名)。

是的,与C#/ Java相比,这看起来像是肮脏的骇客。请记住,接口仅是设计时。在我的例子,AppServiceMockAppService不是甚至从接口和抽象/基类继承(在现实世界中,他们应该,当然),只要他们的实现方法,一切都会正常工作root(): string

引用NestJS文档中有关此主题的内容

注意

我们使用了ConfigService类,而不是自定义标记,因此我们覆盖了默认实现。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章