module.exports = Self => { Self.remoteMethod('addExpeditionState', { description: 'Update an expedition state', accessType: 'WRITE', accepts: [ { arg: 'expeditions', type: ['object'], required: true, description: 'Array of objects containing expeditionFk and stateCode' } ], returns: { type: 'boolean', root: true }, http: { path: `/addExpeditionState`, 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) throw new Error(`The state code: ${expedition.stateCode} does not exist.`); const typeFk = expeditionStateType.id; const existsExpedition = await models.Expedition.findOne({ fields: ['id'], where: {id: expedition.expeditionFk} }); if (!existsExpedition) throw new Error(`The expedition with id: ${expedition.expeditionFk} does not exist.`); const newExpeditionState = models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, }); promises.push(newExpeditionState); } await Promise.all(promises); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }; };