在activerecord模式下使用TypeORM时,如何将事务应用到TypeORM?

pup*_*eno 5 transactions typeorm typeorm-activerecord

我在活动记录模式下使用 TypeORM,并且想应用事务。特别是,我希望每个测试都包含在一个事务中,因此,实现这样的目标:

beforeEach(async () => {
  // start transaction
})

afterEach(async () => {
  // rollback transacttion
})

test("create new", async () => {
  // create new
}
Run Code Online (Sandbox Code Playgroud)

所以,我尝试了这个:

let queryRunner: any

beforeEach(async () => {
  queryRunner = getConnection().createQueryRunner()
  await queryRunner.connect()
  await queryRunner.startTransaction()
})

afterEach(async () => {
  await queryRunner.rollbackTransaction()
  await queryRunner.release()
})

test("Create user", async () => {
  let user = new User()
  await user.save()
})
Run Code Online (Sandbox Code Playgroud)

但看起来这些事务是在单独的上下文/连接上启动的,因为测试运行后,我可以看到数据库中的记录。

如何让交易影响被保存的用户?

小智 -1

我认为您必须将查询运行器连接到数据库。尝试按如下方式修改您的代码:

let queryRunner = getConnection().createQueryRunner()
await queryRunner.connect()
await queryRunner.startTransaction()
let user = new User()
await user.save()
await queryRunner.rollbackTransaction()
await queryRunner.release()
Run Code Online (Sandbox Code Playgroud)

另外,您应该使用 try-catch-finally 块。