From 0ef730d7e416087eac29ff30b89d723dae87f854 Mon Sep 17 00:00:00 2001 From: chenos Date: Thu, 26 Aug 2021 22:03:16 +0800 Subject: [PATCH] fix: call rollback in catch --- packages/actions/src/actions/common.ts | 31 +++++++++++++++----------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/actions/src/actions/common.ts b/packages/actions/src/actions/common.ts index de2e4233c..3bc70e619 100644 --- a/packages/actions/src/actions/common.ts +++ b/packages/actions/src/actions/common.ts @@ -255,21 +255,26 @@ export async function create(ctx: Context, next: Next) { const transaction = await ctx.db.sequelize.transaction(); const options = { transaction, context: ctx }; let model: Model; - if (associated && resourceField) { - const AssociatedModel = ctx.db.getModel(associatedName); - if (!(associated instanceof AssociatedModel)) { - throw new Error(`${associatedName} associated model invalid`); + try { + if (associated && resourceField) { + const AssociatedModel = ctx.db.getModel(associatedName); + if (!(associated instanceof AssociatedModel)) { + throw new Error(`${associatedName} associated model invalid`); + } + const { create } = resourceField.getAccessors(); + model = await associated[create](values, options); + } else { + const ResourceModel = ctx.db.getModel(resourceName); + model = await ResourceModel.create(values, options); } - const { create } = resourceField.getAccessors(); - model = await associated[create](values, options); - } else { - const ResourceModel = ctx.db.getModel(resourceName); - model = await ResourceModel.create(values, options); + await model.updateAssociations(values, options); + await transaction.commit(); + ctx.body = model; + await next(); + } catch (error) { + await transaction.rollback(); + throw error; } - await model.updateAssociations(values, options); - await transaction.commit(); - ctx.body = model; - await next(); } /**