transactions - 使用 NestJS 和 TypeORM 进行交易 - 装饰器和单元测试
问题描述
我的问题是关于使用nestjs 和Typeorm 的事务管理,我的数据库是postgres。
在进行事务管理时是否应该使用 @Transaction 和 @TransactionManager 之类的装饰器。我听说它们将在新版本中被删除。 https://github.com/typeorm/typeorm/issues/3251
作为最佳实践,我们如何处理插入或更新多个表的事务。我看到下面的问题 nestjs / TypeOrm database transaction Is this the right away,有人能给我一个完整的例子。我应该向我的服务类注入连接并从中获取 EntityManager 并传递它吗?
在两个表上对这样的插入进行单元测试的正确方法是什么。
我现在正在使用来自 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);
});
对上述代码进行单元测试的最佳方法是什么?
解决方案
我最终使用了 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");
}
有了它,您可以独立测试您的服务,也可以测试您的控制器以及托管事务
推荐阅读
- neo4j - 在 Neo4j 中存储元数据的有效方法
- nativescript - 如何在组件 nativescript 中显示来自函数的数据?
- javascript - 如何遍历 Puppeteer 创建的屏幕截图图像的像素颜色并绘制矩形并保存到文件
- hive - 将配置单元表作为单个文件输出到 HDFS
- java - gradle mutlimodule 项目中使用 Jacoco 离线检测的跨模块代码覆盖率
- swift - 在 SwiftUI 中为 TotalValue 添加列表值
- rest - Google Firestore - 通过 Postman 进行 REST 读/写
- php - 为 AWS RDS MySQL 启用 TLS 证书验证
- angularjs - 如何将 angularjs 指令和 angular 组件组装在一起?
- html - react.js (gatsby.js) 的模板引擎