我对交易有一些疑问TypeORM。所以我的代码如下:
public createOrderTransaction = async (
data: CreateOrderInputDTO,
): Promise<Order> => {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.startTransaction();
try {
const order = await this.createOrder(data);
await this.createOrderRecord(order.id, data);
await queryRunner.commitTransaction();
return order;
} catch (error) {
this.logger.error(
"Transaction Error: 'createOrderTransaction' is failed: ",
error,
);
if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction();
}
}
};
还有一个功能,例如createOrder使用查询生成器:
private createOrder = async (data: CreateOrderInputDTO): Promise<Order> => {
const { identifiers } = await this.orderRepository
.createQueryBuilder('order')
.insert()
.into(Order)
.values([data])
.execute();
await this.saveOrderDetail(identifiers[0].id, data.orderDetails);
await this.orderRepository
.createQueryBuilder('order')
.relation(Order, 'orderDetails')
.of(identifiers[0].id)
.add(data.orderDetails);
return this.getOrder(identifiers[0].id);
};
但是当我尝试它时,如果它在逻辑中间触发了一些错误,回滚就不起作用。在我看来,它似乎query builder不支持交易。那么有什么方法可以使用quert builderwithtransaction吗?