与NestJS和TypeORM的事务-装饰器和单元测试

问题描述 投票:2回答:1

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

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

  2. 作为最佳实践,我们如何处理正在插入或更新多个表的事务。我看到以下问题nestjs / TypeOrm database transaction这是权利,有人可以给我一个完整的例子。我应该向服务类注入连接并从中获取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);
});

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

transactions nestjs typeorm
1个回答
0
投票

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

这样,您可以独立测试服务,也可以测试控制器的托管交易

© www.soinside.com 2019 - 2024. All rights reserved.