首页 > 解决方案 > 使用 NestJS 和 TypeORM 进行交易 - 装饰器和单元测试

问题描述

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

  1. 在进行事务管理时是否应该使用 @Transaction 和 @TransactionManager 之类的装饰器。我听说它们将在新版本中被删除。 https://github.com/typeorm/typeorm/issues/3251

  2. 作为最佳实践,我们如何处理插入或更新多个表的事务。我看到下面的问题 nestjs / TypeOrm database transaction Is this the right away,有人能给我一个完整的例子。我应该向我的服务类注入连接并从中获取 EntityManager 并传递它吗?

  3. 在两个表上对这样的插入进行单元测试的正确方法是什么。

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

@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);
});

对上述代码进行单元测试的最佳方法是什么?

标签: transactionsnestjstypeorm

解决方案


我最终使用了 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");
                }

有了它,您可以独立测试您的服务,也可以测试您的控制器以及托管事务


推荐阅读