const NotFoundError = require('vn-loopback/util/not-found-error'); module.exports = Self => { Self.remoteMethod('pitInstance', { description: 'Gets the status of instance at specific point in time', accepts: [ { arg: 'id', type: 'integer', description: 'The log id', required: true } ], returns: { type: [Self], root: true }, http: { path: `/:id/pitInstance`, verb: 'GET' } }); Self.pitInstance = async function(id) { const log = await Self.findById(id, { fields: [ 'changedModel', 'changedModelId', 'creationDate' ] }); if (!log) throw new NotFoundError(); const where = { changedModel: log.changedModel, changedModelId: log.changedModelId }; const createdWhere = { action: 'insert', creationDate: {lte: log.creationDate} }; const createdLog = await Self.findOne({ fields: ['id', 'creationDate'], where: Object.assign(createdWhere, where), order: 'creationDate DESC' }); if (!createdLog) throw new NotFoundError('Cannot find creation log'); const logsWhere = { id: {between: [ Math.min(id, createdLog.id), Math.max(id, createdLog.id) ]}, creationDate: {between: [ createdLog.creationDate, log.creationDate ]} }; const logs = await Self.find({ fields: ['newInstance'], where: Object.assign(logsWhere, where), order: 'creationDate' }); if (!logs.length) throw new NotFoundError('No logs found for record'); const instance = {}; for (const log of logs) Object.assign(instance, log.newInstance); return instance; }; };