Mar*_*cin 5 domain-driven-design unit-of-work repository-pattern sequelize.js typescript
我正在尝试在现有项目中使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:出于问题演示目的,代码并不完整且经过简化。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
最后有了CreatePostWithComments 用例Post,我想保存带有附加注释的聚合。我想正确使用工作单元模式在单个 MySQL 事务中完成此操作。
我将不胜感激任何使用简单示例指示正确实施的帮助。
我找到了以下包:https://github.com/pilagod/uow-sequelize,但是由于文档不足,我不知道如何正确使用它。