问题描述
我试图在之后,在现有项目中使用 Sequelize 和Typescript实现存储库和工作单元模式。域驱动设计。但是,由于缺乏相关示例,我遇到了一些困难。
让我们考虑以下代码示例。
interface IPostRepo {
save(post: Post): Promise<void>;
}
interface ICommentRepo {
save(comment: Comment): Promise<void>;
saveBulk(comments: Comment[]): Promise<void>;
}
class SequelizePostRepo implements IPostRepo {
private models: any;
private commentRepo: ICommentRepo;
constructor(models: any,commentRepo: ICommentRepo) {
this.models = models;
this.commentRepo = commentRepo;
}
public async save(post: Post): Promise<void> {
const PostModel = this.models.Post;
const rawSequelizePost = await PostMap.toPersistence(post);
await PostModel.create(rawSequelizePost);
await this.commentRepo.saveBulk(comments);
}
}
class SequelizeCommentRepo implements ICommentRepo {
private models: any;
constructor(models: any) {
this.models = models;
}
async save(comment: Comment): Promise<void> {
const CommentModel = this.models.Comment;
const rawSequelizeComment = CommentMap.toPersistence(comment);
await CommentModel.create(rawSequelizeComment);
}
async saveBulk(comments: Comment[]): Promise<void> {
for (let comment of comments) {
await this.save(comment);
}
}
}
注意:该代码不完整且出于问题演示目的而被简化。
IPostRepo
和ICommentRepo
是用于特定实现的合同,例如SequelizePostRepo
和SequelizeCommentRepo
。
它们都实现了对域实体进行操作的基本保存方法:Post
和Comment
。 Post
是聚合根(模型对象包含基本的Sequelize模型定义)。
class CreatePostWithComments implements UseCase {
private postRepo: IPostRepo;
constructor (postRepo: IPostRepo) {
this.postRepo = postRepo;
}
public async execute (req: ReplyToPostDTO) {
/**
*
* More logic related to post and comments creation goes here
*
*/
post.addComment(comment1);
post.addComment(comment2);
post.addComment(comment3);
await this.postRepo.save(post);
}
}
最后有CreatePostWithComments
个用例,我想保存Post
,并附加注释。我想使用工作单元模式正确地在单个MysqL事务中完成此操作。
对于使用简单示例说明正确实施的任何帮助,我将不胜感激。
我找到了以下软件包:https://github.com/pilagod/uow-sequelize,但是由于文档不足,我不知道如何正确使用它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)