const UserError = require('vn-loopback/util/user-error'); const LoopBackContext = require('loopback-context'); module.exports = Self => { Self.rewriteDbError(function(err) { if (err.code === 'ER_DUP_ENTRY') return new UserError(`The observation type can't be repeated`); return err; }); Self.observe('before save', async function(ctx, options) { const loopBackContext = LoopBackContext.getCurrentContext(); const userId = loopBackContext.active.accessToken.userId; const entryId = ctx.instance.entryFk; let tx; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const entry = await Self.app.models.Entry.findById(entryId, null, myOptions); await entry.updateAttribute('observationEditorFk', userId, myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }); };