我发现了许多嵌套“示例”应用程序的示例,但每个示例似乎对设计模式都有略微不同的看法。 我目前感兴趣的是,当与 TypeORM 结合使用时,对象准备工作应该在解析器和服务之间进行。
例如:
comment.resolver.ts:
/********************
* @MUTATION
*********************/
/**
*
* @param payload
* @param args
*/
@Mutation('createComment')
async create(@CurrentUser() payload: JwtPayload, @Args('input') args: CreateCommentInputDto): Promise < CommentEntity > {
const currentUser = await this.userService.getCurrentUser(payload);
const initComment = new CommentEntity();
const newComment: CommentEntity = {
...args,
createdBy: currentUser,
createdDate: new Date(),
modifiedDate: new Date(),
...initComment,
};
const createdComment = await this.commentService.create(newComment);
pubSub.publish('CommentCreated', {
CommentCreated: createdComment
});
return createdComment;
}
评论.service.ts:
/**
*
* @param comment
*/
async create(comment: CommentEntity): Promise < CommentEntity > {
return await this.CommentsRepository.save(comment);
}
即
- 创建新的空评论实体
- 添加查询未提供的字段值
- 使用扩展运算符将它们组合在一起
- 将它们全部传递给评论服务以通过 TypeORM 存储库保存
原因是评论服务只接受并保存格式良好的实体。也许将来我需要准备以不同方式创建的注释,以便在新的突变中定义它。
这是一种反模式吗?我是否应该将该对象创建/组合/格式化移动到服务中,并保持解析器方法尽可能简单?
如果是这样,其背后的逻辑是什么?
最佳答案
您应该检查 TypeOrm 提供的 Repository
项提供的 preload
方法。它允许对现有实体或新实体进行批量更改,这应该是您想要的。
我认为 TypeOrm 非常不固定,你可以自由选择如何组织实体上的突变。不过,我认为“预加载”存储库模式是一种安全的模式,因为您总是希望首先从数据库中获取与您建议的更改相对应的值,然后对实体中的更改进行批处理并随后保存。它应该会降低您在实体上获得冲突值或获得双倍值等的机会。
您可以将数据库视为 git 存储库,首先获取,将本地更改重新设置为远程 header value ,然后提交并推送更改。
关于node.js - NestJS + TypeORM 设计模式 : resolver vs service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571521/