【问题标题】:Getting decoupled modules in NestJS在 NestJS 中获取解耦模块
【发布时间】:2020-01-14 09:53:18
【问题描述】:

我似乎不知道如何根据自己的喜好在 NestJS 中使用依赖注入。

这是我的项目结构:

App --- User ------ Common
  \ \-- Article --/
   \--- Chat

简而言之:一个大的应用程序模块就是应用程序。功能模块userarticlechat。现在如果某个功能想要与其他功能交互,它需要依赖common 模块。

在我的简单情况下,这将是: 文章数据库有关于作者的简单对象。因此,一旦它检索到文章数据,它就想检索作者(用户)的数据。但它一定不能在user 模块上看到。

我的解决方案是在公共模块中使用service 接口。

export interface UserCommonService {
    getUser(id: string): Promise<User | null>
}

真正的UserService 将实现这个公共服务,并且通过依赖注入我可以在控制器中得到它而不依赖于user 模块。

@Injectable()
export class UserService implements UserCommonService {
  async getUser(id: string): Promise<User | null> {
    ...
  }
}

@ApiTags("v1/article")
@Controller("v1/article")
export class ArticleController {
  constructor(
    private readonly articleService: ArticleService,
    @Inject('UserService') private readonly userService: UserCommonService
  ) { }

  @Get(":id")
  async getArticle(@Param("id") id: string): Promise<...> {
    const article = await this.articleService.getArticle(id)
    const user = await this.userService.getUser(article.author.id)

    return {author: user, article: article}
  }
}

现在我不知道如何在 DI 模块中完成这项工作。据我所知,我关注user.module.ts

@Module({
  imports: [TypegooseModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService, { provide: 'UserService', useClass: UserService }],
  exports: ['UserService']
})

但我不知道在article.module 中输入什么来导入它。或者也许是app.module?我所做的一切都会导致错误或不可能 - 比如导入不能有字符串值。 任何帮助表示赞赏。

【问题讨论】:

    标签: architecture nestjs decoupling


    【解决方案1】:

    两件事:

    在您的 user.module.ts 中,您应该只在 providers 数组中有一次 UserService,然后像这样导出

    @Module({
      imports: [TypegooseModule.forFeature([User])],
      controllers: [UserController],
      providers: [{ provide: 'UserService', useClass: UserService }],
      exports: ['UserService']
    })
    export class UserModule {}
    

    我建议将 'UserService' 字符串更改为常量或 symbol 以使其可重复使用而不会拼写错误,但这取决于您。

    然后在你的article.module.ts 中允许@Inject('UserService') 你只需要像这样导入UserModule

    @Module({
      imports: [UserModule, TypegooseModule.forFeature([Article]),
      controller: [ArticleController],
      providers: [ArticleService]
    })
    export class ArticleModule {}
    

    Nest 不应该为此抱怨任何错误。如果您遇到任何问题,请告诉我

    【讨论】:

    • 你是对的,没有错误,它按预期工作:) 但是,我在文章中仍然有用户依赖。具体来说,我在 article.module 中导入了 user.module。它好多了,但还不是我的想法。
    • 如果您不想在任何其他模块中重用任何模块,一个选择是重新声明模型的 TypegooseModule 依赖项:User,然后进行直接查询而不是通过 UserService,但是使用这种方法,您很可能会得到重复的代码。目前,您不必依赖于UserModule,只需依赖于提供UserService 令牌提供程序的a 模块。
    • 好吧,我认为这是 Nestjs 的设计缺陷,并尽可能接受您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2019-06-15
    相关资源
    最近更新 更多