【发布时间】:2020-01-14 09:53:18
【问题描述】:
我似乎不知道如何根据自己的喜好在 NestJS 中使用依赖注入。
这是我的项目结构:
App --- User ------ Common
\ \-- Article --/
\--- Chat
简而言之:一个大的应用程序模块就是应用程序。功能模块user、article 和chat。现在如果某个功能想要与其他功能交互,它需要依赖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