const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('addExpeditionState', { description: 'Update an expedition state', accessType: 'WRITE', accepts: [ { arg: 'expeditions', type: ['object'], required: true, description: 'Array of objects containing expeditionFk and stateCode' } ], http: { path: `/addExpeditionState`, verb: 'post' } }); Self.addExpeditionState = async(ctx, expeditions, options) => { const models = Self.app.models; const userId = ctx.req.accessToken.userId; let tx; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } let expeditionId; try { for (const expedition of expeditions) { const expeditionStateType = await models.ExpeditionStateType.findOne( { fields: ['id'], where: {code: expedition.stateCode} }, myOptions ); if (!expeditionStateType) throw new UserError(`Invalid state code: ${expedition.stateCode}.`); const typeFk = expeditionStateType.id; expeditionId = expedition.expeditionFk; await models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, userFk: userId, }, myOptions); } if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); if (e instanceof UserError) throw e; throw new UserError(`Invalid expedition id: ${expeditionId}.`); } }; };