69 lines
2.0 KiB
JavaScript
69 lines
2.0 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethod('addExpeditionState', {
|
|
description: 'Update an expedition state',
|
|
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(
|
|
{
|
|
fields: ['id'],
|
|
where: {code: expedition.stateCode}
|
|
}
|
|
);
|
|
|
|
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;
|
|
}
|
|
};
|
|
};
|