Architecture 在NestJS中获取解耦模块

Architecture 在NestJS中获取解耦模块,architecture,nestjs,decoupling,Architecture,Nestjs,Decoupling,我似乎不知道如何根据自己的喜好在NestJS中使用依赖注入 以下是我的项目结构: App --- User ------ Common \ \-- Article --/ \--- Chat 换句话说:一个大的应用程序模块就是应用程序。功能模块用户,文章和聊天。现在,如果某个功能想要与其他功能交互,它需要依赖于common模块 在我的简单案例中,这将是: 文章数据库有关于作者的简单对象。因此,一旦检索到文章数据,它就要检索作者(用户)的数据。但它不能在用户模块上看到 我的解决方案是在

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

以下是我的项目结构:

App --- User ------ Common
  \ \-- Article --/
   \--- Chat
换句话说:一个大的应用程序模块就是应用程序。功能模块
用户
文章
聊天
。现在,如果某个功能想要与其他功能交互,它需要依赖于
common
模块

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

我的解决方案是在公共模块中有
服务
接口

导出接口UserCommonService{
getUser(id:string):承诺
}
Real
UserService
将实现这个公共服务,通过依赖项注入,我将在控制器中获得它,而不依赖于
user
模块

@Injectable()
导出类UserService实现UserCommonService{
异步getUser(id:string):承诺{
...
}
}
@ApiTags(“v1/文章”)
@控制器(“v1/物品”)
导出类控制器{
建造师(
专用只读articleService:articleService,
@Inject('UserService')私有只读用户服务:UserCommonService
) { }
@获取(“:id”)
异步getArticle(@Param(“id”)id:string):承诺{
const article=等待此.articleService.getArticle(id)
const user=wait this.userService.getUser(article.author.id)
返回{作者:用户,文章:文章}
}
}
现在我不知道如何在DI模块中实现这一点。据我所知,我在
user.module.ts

@模块({
导入:[TypegooseModule.forFeature([User])],
控制器:[UserController],
提供者:[UserService,{Provider:'UserService',useClass:UserService}],
导出:['UserService']
})
但是我不知道在
article.module中放入什么来导入它。或者可能是到
app.module
?我所做的每件事都会导致错误或不可能,比如导入不能有字符串值。 感谢您的帮助。

两件事:

user.module.ts
中,提供者数组中应该只包含一次
UserService
,并像这样导出

@模块({
导入:[TypegooseModule.forFeature([User])],
控制器:[UserController],
提供程序:[{provide:'UserService',useClass:UserService}],
导出:['UserService']
})
导出类UserModule{}
我建议将
'UserService'
字符串更改为常量或
符号
,以使其可重用,而不可能拼写错误,但这取决于您

然后在您的
文章.module.ts
中,为了允许
@Inject('UserService')
您只需要像这样导入
UserModule

@模块({
导入:[UserModule,TypeGoosModule.forFeature([Article]),
控制器:[ArticleController],
提供者:[条款服务]
})
导出类ArticleModule{}

Nest不应该为此抱怨任何错误。如果您遇到任何问题,请告诉我您是对的,没有错误,并且它可以按预期工作:)但是,我在文章中仍然具有用户依赖性。具体地说,我在article.module中导入了user.module。它要好得多,但还不是我所想的。如果您需要,请选择一个st不想在任何其他模块中重用任何模块,就是重新声明model:
User
的TypeGoosModule依赖关系,然后进行直接查询,而不是通过
UserService
,但是使用这种方法,您很可能会得到重复的代码Server模块<代码>,只在提供<代码> UService < /Cord>令牌提供者的模块上。好吧,我认为这是Nestjs设计缺陷,并将您的解决方案视为可能的最佳方案。