与 NestJS 和 TypeORM 的交易——装饰器和单元测试

Transactions with NestJS and TypeORM - decorators and unit tesing

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

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

  2. 作为最佳实践,我们如何处理插入或更新多个表的事务。我看到以下问题 这是马上吗,有人可以给我一个完整的例子吗?我应该将连接注入到我的服务 class 并从中获取 EntityManager 并传递它吗?

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

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

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

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

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

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