72 lines
2.0 KiB
JavaScript
72 lines
2.0 KiB
JavaScript
|
const UserError = require('vn-loopback/util/user-error');
|
||
|
|
||
|
module.exports = Self => {
|
||
|
Self.remoteMethod('updateExpedtionState', {
|
||
|
description: 'Update an expedition state',
|
||
|
accepts: [
|
||
|
{
|
||
|
arg: 'expeditions',
|
||
|
type: [
|
||
|
{
|
||
|
expeditionFk: 'number',
|
||
|
stateCode: 'string'
|
||
|
}
|
||
|
],
|
||
|
required: true,
|
||
|
description: 'Array of objects containing expeditionFk and stateCode'
|
||
|
}
|
||
|
],
|
||
|
http: {
|
||
|
path: `/updateExpeditionState`,
|
||
|
verb: 'post'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.updateExpedtionState = 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;
|
||
|
}
|
||
|
|
||
|
if (expeditions.length === 0)
|
||
|
return false;
|
||
|
|
||
|
const promises = [];
|
||
|
try {
|
||
|
const conn = Self.dataSource.connector;
|
||
|
for (const expedition of expeditions) {
|
||
|
const stmt = new ParameterizedSQL(
|
||
|
`SELECT id FROM vn.expeditionStateType WHERE code = ?`,
|
||
|
[expedition.stateCode]
|
||
|
);
|
||
|
const result = await conn.query(stmt);
|
||
|
if (result.length === 0)
|
||
|
throw new Error(`The state code '${exp.stateCode}' does not exist.`);
|
||
|
|
||
|
const typeFk = result[0].id;
|
||
|
|
||
|
const newExpeditionState = await models.Self.create({
|
||
|
expeditionFk: expedition.expeditionFk,
|
||
|
typeFk,
|
||
|
});
|
||
|
}
|
||
|
|
||
|
await Promise.all(promises);
|
||
|
|
||
|
if (tx) await tx.commit();
|
||
|
|
||
|
return true;
|
||
|
} catch (e) {
|
||
|
if (tx) await tx.rollback();
|
||
|
throw e;
|
||
|
}
|
||
|
};
|
||
|
};
|