I want to keep an history of changes made to an entity. For example, user entity:
{
name: 'Raz',
places_visited: [
{ city: 'Jerusalem', street: 'King David', house_number: 10 }
]
}
Then these kind of changes may apply:
- name ‘Raz’ has updated to ‘Raziel’
- The first place he visited has updated from house_number 10 to house_number 20
- A new place has been inserted on top (he visited this place before the place that already in, like unshift):
{ city: 'Tel Aviv', street: 'Ibn Gabirol', house_number: 30 }
I want to store those changes somehow, probably in the DB in a dedicated History collection that will store just any changes, regardless the user entity. The history collection may look like this and have these fields:
EntityType, EntityId, KeyChanged, OldValue, NewValue, …(IAT and By and etc)
So in our case, the history collection should contain the next 3 rows:
- user, 123, name, Raz, Raziel, today, by admin
- user, 123, places_visited.0.house_number, 10, 20, today, by admin
- user, 123, places_visited.0,
{ city: 'Jerusalem', street: 'King David', house_number: 20 },{ city: 'Tel Aviv', street: 'Ibn Gabiron', house_number: 30 }, today, by admin, - user, 123, places_visited.1, undefined,
{ city: 'Jerusalem', street: 'King David', house_number: 20 }, today, by admin
I have tried to use the JS new built in Proxy class:
const handler = {
prefix: '',
get(target, prop) {
if (typeof target[prop] === "object" && target[prop] !== null) {
handler.prefix += `${prop}.`
return new Proxy(target[prop], handler)
}
return target[prop]
},
set(target, prop, newValue) {
const oldValue = target[prop]
target[prop] = newValue
if (oldValue !== newValue) {
console.log(oldValue, newValue)
}
return true
}
}
const proxy = new Proxy(user, handler)
However, when using methods like push, unshift or so, are getting messy and the tracking is getting ruined.
How this can be achieved?