Transaction refactor
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Joan Sanchez 2021-08-06 12:24:36 +02:00
parent ce37f982c4
commit 9dc1168ad2
1 changed files with 14 additions and 15 deletions

View File

@ -11,11 +11,6 @@ module.exports = Self => {
description: 'The entry id', description: 'The entry id',
http: {source: 'path'} http: {source: 'path'}
}, },
{
arg: 'options',
type: 'object',
description: 'Callback options',
},
{ {
arg: 'ref', arg: 'ref',
type: 'string', type: 'string',
@ -28,11 +23,11 @@ module.exports = Self => {
}, },
{ {
arg: 'buys', arg: 'buys',
type: ['Object'], type: ['object'],
description: 'The buys', description: 'The buys',
}], }],
returns: { returns: {
type: ['Object'], type: ['object'],
root: true root: true
}, },
http: { http: {
@ -41,23 +36,27 @@ module.exports = Self => {
} }
}); });
Self.importBuys = async(ctx, id, options = {}) => { Self.importBuys = async(ctx, id, options) => {
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
const args = ctx.args; const args = ctx.args;
const models = Self.app.models; const models = Self.app.models;
let tx; let tx;
const myOptions = {};
if (!options.transaction) { if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({}); tx = await Self.beginTransaction({});
options.transaction = tx; myOptions.transaction = tx;
} }
try { try {
const entry = await models.Entry.findById(id, null, options); const entry = await models.Entry.findById(id, null, myOptions);
await entry.updateAttributes({ await entry.updateAttributes({
observation: args.observation, observation: args.observation,
ref: args.ref ref: args.ref
}, options); }, myOptions);
const buys = []; const buys = [];
for (let buy of args.buys) { for (let buy of args.buys) {
@ -77,10 +76,10 @@ module.exports = Self => {
name: buy.description, name: buy.description,
producer: buy.companyName, producer: buy.companyName,
size: buy.size size: buy.size
}, options); }, myOptions);
} }
const createdBuys = await models.Buy.create(buys, options); const createdBuys = await models.Buy.create(buys, myOptions);
const buyIds = createdBuys.map(buy => buy.id); const buyIds = createdBuys.map(buy => buy.id);
const stmts = []; const stmts = [];
@ -97,7 +96,7 @@ module.exports = Self => {
stmts.push('CALL buy_recalcPrices()'); stmts.push('CALL buy_recalcPrices()');
const sql = ParameterizedSQL.join(stmts, ';'); const sql = ParameterizedSQL.join(stmts, ';');
await conn.executeStmt(sql, options); await conn.executeStmt(sql, myOptions);
if (tx) await tx.commit(); if (tx) await tx.commit();
} catch (e) { } catch (e) {
if (tx) await tx.rollback(); if (tx) await tx.rollback();