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' } ], http: { path: `/addExpeditionState`, verb: 'post' } }); Self.updateExpedtionState = async(expeditions, options) => { console.log('Expeditions!!!!!!!!', expeditions); 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 { const conn = Self.dataSource.connector; for (const expedition of expeditions) { const expeditionStateType = await models.expeditionStateType.findOne( { fields: ['id'], where: {code: expedition.stateCode} } ); const result = await conn.query(stmt); if (!expeditionStateType.id) throw new Error(`The state code '${expedition.stateCode}' does not exist.`); const typeFk = result.id; const newExpeditionState = models.Self.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(); throw e; } }; };