const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('allocatePDA', { description: 'Deallocate the PDA of the worker', accepts: [{ arg: 'id', type: 'number', required: true, description: 'The worker id', http: {source: 'path'} }, { arg: 'pda', type: 'number', required: true, description: 'The pda id' }], returns: { type: ['object'], root: true }, http: { path: `/:id/allocatePDA`, verb: 'POST' } }); Self.allocatePDA = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; let tx; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const pda = await models.DeviceProduction.findById(args.pda, myOptions); if (pda.stateFk != 'idle') throw new UserError(`The PDA state is not idle`); await pda.updateAttributes({stateFk: 'active'}, myOptions); await models.DeviceProductionUser.create({ deviceProductionFk: args.pda, userFk: args.id, created: new Date() }, myOptions); if (tx) await tx.commit(); return { deviceProductionFk: pda.id, deviceProduction: { modelFk: pda.modelFk, serialNumber: pda.serialNumber } }; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };