Skip to content

Commit

Permalink
Merge pull request #16 from ks-labs/refact-different-objects
Browse files Browse the repository at this point in the history
Refactoring
  • Loading branch information
vinicioslc authored Feb 27, 2024
2 parents f5c1219 + dc68629 commit e6e0613
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 25 deletions.
25 changes: 25 additions & 0 deletions src/Helpers/DifferentData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Return only the values ​​that have changed
* @param {object} oldData
* @param {object} newData
* @typedef {object} result
*/
module.exports = function differentData(oldData, newData) {
let result = { oldData: {}, newData: {} }
if (!Object.keys(oldData).length) {
result.newData = newData
} else {
for (let prop in oldData) {
if (newData.hasOwnProperty(prop)) {
const value1 = oldData[prop]
const value2 = newData[prop]
if (value1 !== value2) {
result.oldData[prop] = value1
result.newData[prop] = value2
}
} else {
}
}
}
return result
}
29 changes: 4 additions & 25 deletions src/Traits/Auditable.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,10 @@

const _ = require('lodash')
const { AuditableInvalidRelationshipError } = require('../Exceptions')
const differentData = require('../Helpers/DifferentData')
/** @type {typeof import('../../templates/Audit')} */
const Audit = use('App/Models/Audit')

/**
* Return only the values ​​that have changed
* @param {*} objectA
* @param {*} objectB
* @returns {Object, Object} Object
*/

function differenceObj(objectA, objectB) {
let result = { oldValue: {}, newValue: {} }
for (let prop in objectA) {
if (objectB.hasOwnProperty(prop)) {
const value1 = objectA[prop]
const value2 = objectB[prop]
if (value1 !== value2) {
result.oldValue[prop] = value1
result.newValue[prop] = value2
}
}
}
return result
}

/**
* Validates all relations and raise appropiate exceptions when missing
* this indeed to be used as validation function
Expand Down Expand Up @@ -183,9 +162,9 @@ function updateWithAudit(ctx, opts, relationsFn) {
return persisted
}

const { oldValue, newValue } = differenceObj(oldData, newData)
oldData = oldValue
newData = newValue
const difference = differentData(oldData, newData)
oldData = difference.oldData
newData = difference.newData

// update / patch are shared
const event = Audit.events.UPDATE
Expand Down

0 comments on commit e6e0613

Please sign in to comment.