使用NestJS和TypeORM进行事务处理 - 装饰器和单元测试

3

我的问题与使用nestjs和Typeorm进行事务管理有关,我的数据库是postgres。

  1. 在进行事务管理时,我应该使用@Transaction和@TransactionManager等装饰器吗? 我听说它们将在新版本中被移除。 https://github.com/typeorm/typeorm/issues/3251

  2. 作为最佳实践,我们如何处理插入或更新多个表的事务。我看到以下问题 nestjs / TypeOrm database transaction 这是正确的方式吗?有人能给我一个完整的例子吗?我应该将连接注入到我的服务类中,并从中获取EntityManager并将其传递吗?

  3. 对于单元测试这样在两个表中进行插入,哪种方式是正确的?

我现在使用TypeOrm的Transaction装饰器。 所有我的创建代码都在一个类中,我希望能够将每个实体的创建代码移到实体自己的服务类中,并期望事务回滚仍然有效。

@Transaction({ isolation: "SERIALIZABLE" })
    async createProfile(createProfileDTO: CreateProfileDTO, @TransactionManager() manager?: EntityManager){
...
const profileRepository = manager.getRepository(Profile);
let savedProfile = await profileRepository.save<Profile>(profile);

identifier.profile = savedProfile;
 const identifierRepository = manager.getRepository(Identifier);
 let savedIdentifier = identifierRepository.save(identifier);

}

另外,如果我使用

 await this.connection.transaction(async transactionalEntityManager => {
            profile = await this.createUserProfile(createProfileDTO, transactionalEntityManager);
            identifiers = await this.identifierService.createIdentifier(profile, createProfileDTO
                , transactionalEntityManager);
});

什么是测试上述代码的最佳方法?
1个回答

2
我最终使用了一个Connection对象而不是装饰器。
@InjectConnection()
private readonly connection: Connection)

然后像这样调用所有的服务

await this.connection.transaction(async transactionalEntityManager => {
                try {
                    urDTOCreated = await this.myService1.createSomething(urDTO, transactionalEntityManager);
                    typeDTOCreated = await this.myService2.createSomethingElse(obj1, obj2, transactionalEntityManager);
                }
                catch (ex) {
                    Logger.log(ex);
                    throw new InternalServerErrorException("Error saving data to database");
                }

这样,您就可以独立测试您的服务,并且还可以为受控事务测试您的控制器。


7
每次都要将transactionalEntityManager传递给使用的每个函数有点麻烦。我将研究替代方案,但在我深入挖掘之前,有没有其他人解决过这个问题? - Ray
@Ray 你有找到更好的选择吗? - ps-aux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接