salix/modules/ticket/back/methods/expedition-state/addExpeditionState.js

69 lines
2.0 KiB
JavaScript
Raw Normal View History

module.exports = Self => {
2023-07-26 10:36:30 +00:00
Self.remoteMethod('addExpeditionState', {
description: 'Update an expedition state',
2023-07-26 10:36:30 +00:00
accessType: 'WRITE',
accepts: [
{
arg: 'expeditions',
type: [{
expeditionFk: 'number',
stateCode: 'string',
}],
required: true,
description: 'Array of objects containing expeditionFk and stateCode'
}
],
returns: {
type: 'boolean',
root: true
},
http: {
path: `/addState`,
verb: 'post'
}
});
Self.addExpeditionState = async(expeditions, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const promises = [];
try {
for (const expedition of expeditions) {
const expeditionStateType = await models.ExpeditionStateType.findOne(
2023-07-26 10:36:30 +00:00
{
fields: ['id'],
where: {code: expedition.stateCode}
}
);
2023-07-26 10:36:30 +00:00
if (!expeditionStateType.id)
throw new Error(`The state code '${expedition.stateCode}' does not exist.`);
const typeFk = expeditionStateType.id;
const newExpeditionState = models.ExpeditionState.create({
expeditionFk: expedition.expeditionFk,
typeFk,
});
promises.push(newExpeditionState);
}
await Promise.all(promises);
if (tx) await tx.commit();
return true;
} catch (e) {
if (tx) await tx.rollback();
return false;
}
};
};