You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.8 KiB
66 lines
1.8 KiB
5 years ago
|
import jsonDiffer from 'fast-json-patch'
|
||
5 years ago
|
import { cloneDeep } from 'lodash'
|
||
5 years ago
|
|
||
7 years ago
|
/**
|
||
|
converts non-initial history entries into diffs
|
||
5 years ago
|
@param {array} longHistory
|
||
7 years ago
|
@returns {array}
|
||
|
*/
|
||
5 years ago
|
export function migrateFromSnapshotsToDiffs (longHistory) {
|
||
7 years ago
|
return (
|
||
|
longHistory
|
||
|
// convert non-initial history entries into diffs
|
||
5 years ago
|
.map((entry, index) => {
|
||
5 years ago
|
if (index === 0) {
|
||
|
return entry
|
||
|
}
|
||
5 years ago
|
return generateHistoryEntry(longHistory[index - 1], entry)
|
||
|
})
|
||
7 years ago
|
)
|
||
|
}
|
||
|
|
||
7 years ago
|
/**
|
||
7 years ago
|
Generates an array of history objects sense the previous state.
|
||
7 years ago
|
The object has the keys
|
||
7 years ago
|
op (the operation performed),
|
||
|
path (the key and if a nested object then each key will be seperated with a `/`)
|
||
|
value
|
||
|
with the first entry having the note and a timestamp when the change took place
|
||
5 years ago
|
@param {Object} previousState - the previous state of the object
|
||
|
@param {Object} newState - the update object
|
||
5 years ago
|
@param {string} [note] - a optional note for the state change
|
||
7 years ago
|
@returns {array}
|
||
7 years ago
|
*/
|
||
5 years ago
|
export function generateHistoryEntry (previousState, newState, note) {
|
||
7 years ago
|
const entry = jsonDiffer.compare(previousState, newState)
|
||
|
// Add a note to the first op, since it breaks if we append it to the entry
|
||
7 years ago
|
if (entry[0]) {
|
||
5 years ago
|
if (note) {
|
||
|
entry[0].note = note
|
||
|
}
|
||
7 years ago
|
|
||
7 years ago
|
entry[0].timestamp = Date.now()
|
||
7 years ago
|
}
|
||
7 years ago
|
return entry
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
/**
|
||
|
Recovers previous txMeta state obj
|
||
5 years ago
|
@returns {Object}
|
||
7 years ago
|
*/
|
||
5 years ago
|
export function replayHistory (_shortHistory) {
|
||
5 years ago
|
const shortHistory = cloneDeep(_shortHistory)
|
||
7 years ago
|
return shortHistory.reduce((val, entry) => jsonDiffer.applyPatch(val, entry).newDocument)
|
||
|
}
|
||
|
|
||
7 years ago
|
/**
|
||
5 years ago
|
* Snapshot {@code txMeta}
|
||
|
* @param {Object} txMeta - the tx metadata object
|
||
|
* @returns {Object} a deep clone without history
|
||
|
*/
|
||
5 years ago
|
export function snapshotFromTxMeta (txMeta) {
|
||
5 years ago
|
const shallow = { ...txMeta }
|
||
|
delete shallow.history
|
||
|
return cloneDeep(shallow)
|
||
7 years ago
|
}
|