Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | 'use strict'
const { diff } = require('deep-diff')
const { modelToJSONSchema } = require('./schema-to-json')
const {
set,
get,
map,
omit,
startCase,
camelCase,
compact,
concat,
isEmpty,
isNumber,
includes,
isNil,
result: execute
} = require('lodash')
const OPERATION = { N: 'Created', D: 'Deleted', E: 'Edited', A: 'Array' }
let changes = []
class DiffHelper {
/**
* @author welington Monteiro
* @param { Object } [diffParams.old] - old json
* @param { Object } [diffParams.current] - current json
* @param { Object } [diffParams] - params {old, current}
* @param {{}} schema - paths schema mapped
* @param { Object } [options] - options params
* @param { Array<String> } [options.omitPaths] - options omitPaths params
* @param { String } [options.changeTransform.label] - options changesToView.label {label: 'otherPathName'}
* @param { String } [options.changeTransform.to] - options changesToView.to {to: 'otherPathName'}
* @param { String } [options.changeTransform.from] - options changesToView.from {from: 'otherPathName'}
* @param { String } [options.changeTransform.ops] - options changesToView.ops {ops: 'otherPathName'}
* @param { String } [options.changeTransform.path] - options changesToView.path {path: 'otherPathName'}
* @return { Array } - list of diffs changes
*/
static getDiff (diffParams = {}, schema = {}, options = {}) {
let { old = {}, current = {} } = diffParams
const omitPaths = get(options, 'omitPaths', [])
const defaultOmitPaths = ['_id']
old = omit(old, concat(omitPaths, defaultOmitPaths))
current = omit(current, concat(omitPaths, defaultOmitPaths))
changes = []
const differences = diff(old, current)
DiffHelper._mapItems(differences, schema, options)
return compact(changes)
}
/**
* @author Welington Monteiro
* @param { Array } diffs - deep diffs between old and current
* @param { Schema } schema - paths schema mapped
* @param { Object } [options] - options params
* @return {void}
* @private
*/
static _mapItems (diffs, schema, options) {
map(diffs, _addItem)
function _addItem (item) {
const to = get(item, 'rhs', get(item, 'item.rhs', ''))
const path = item.path.join('.')
const from = get(item, 'lhs', get(item, 'item.lhs', ''))
let ops = OPERATION[get(item, 'kind', '')]
const { index, isArray } = DiffHelper._getIndexIsArray({ item, ops })
if (ops === 'Array') ops = OPERATION[get(item, 'item.kind', '')] || ops
if (DiffHelper._isObject(to)) {
return DiffHelper._objectMapped({ path, item: to, ops, schema, index, isArray }, 'to', options)
}
if (DiffHelper._isObject(from)) {
return DiffHelper._objectMapped({ path, item: from, ops, schema, index, isArray }, 'from', options)
}
const label = DiffHelper._getLabel(path, schema)
const jsonSchema = modelToJSONSchema(schema)
const isOmitted = DiffHelper._omittedFieldsIfNotMapped(path, jsonSchema, options)
if (isOmitted) return
changes.push(DiffHelper._changeTransformToView({ to, path, from, ops, label, index, isArray }, options))
}
}
static unFlattenJson (data) {
if (Object(data) !== data || Array.isArray(data)) {
return data
}
const regex = /\.?([^.[\]]+)|\[(\d+)\]/g
const resultholder = {}
for (const p in data) {
let cur = resultholder
let prop = ''
let m
// eslint-disable-next-line
while (m = regex.exec(p)) {
cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}))
prop = m[2] || m[1]
}
cur[prop] = data[p]
}
return resultholder[''] || resultholder
}
static flatJson (obj, opts, parentProp, $set) {
$set = $set || {}
opts = opts || {}
const json = execute(obj, 'toJSON', obj)
for (const prop in json) {
const value = json[prop]
const newProp = (parentProp ? parentProp + '.' : '') + prop
const isJsonObject = typeof value === 'object' &&
value !== null &&
value !== undefined &&
!(value instanceof Date) &&
!(get(value, 'constructor.name') === 'ObjectID') &&
prop !== '_id'
if (Array.isArray(value)) {
$set[newProp] = value
} else if (isJsonObject) {
DiffHelper.flatJson(value, opts, newProp, $set)
} else {
if (get(opts, 'omitNullAndEmpty')) {
if (!isNil(value) && value !== '') $set[newProp] = value
} else {
$set[newProp] = value
}
}
}
return $set
}
/**
* @author Welington Monteiro
* @description Verify is value is object
* @param { * } value - Value for comparison
* @return { boolean } - return is object
*/
static _isObject (value) {
return Object.prototype.toString.call(value) === '[object Object]'
}
/**
* @author Welington Monteiro
* @param { Object } change - object params
* @param { Object } [options] - options change transform to view
* @return {Object} newChange - object new transformed
*/
static _changeTransformToView (change = {}, options = {}) {
const newChange = { index: null, isArray: false }
if (isEmpty(change)) return null
set(newChange, 'isArray', get(change, 'isArray'))
set(newChange, 'index', get(change, 'index'))
set(newChange, `${get(options, 'changeTransform.to') || 'to'}`, get(change, 'to'))
set(newChange, `${get(options, 'changeTransform.from') || 'from'}`, get(change, 'from'))
set(newChange, `${get(options, 'changeTransform.path') || 'path'}`, get(change, 'path'))
set(newChange, `${get(options, 'changeTransform.ops') || 'ops'}`, get(change, 'ops'))
set(newChange, `${get(options, 'changeTransform.label') || 'label'}`, get(change, 'label'))
return newChange
}
/**
* @author Welington Monteiro
* @param { Object } item - item to mapped fields
* @param { String } ops - type of path
* @return {{index: null, isArray: boolean}} - return object
* @private
*/
static _getIndexIsArray ({ item = {}, ops = '' }) {
let index = get(item, 'index', null)
let isArray = ops === 'Array'
map(get(item, 'path'), (field) => {
if (isNumber(field)) {
index = field
isArray = true
}
})
return { index, isArray }
}
/**
* @author Welington Monteiro
* @param { Object } [params] - item to mapped fields
* @param { Object } [params.item] - item to mapped fields
* @param { String } [params.path] - path fields
* @param { String } [params.ops] - ops mapped
* @param { Object } [params.schema] - paths schema mapped
* @param [params] - params mapped
* @param { String } fieldItem - name field item mapped to object
* @param { Object } [options] - options change transform to view
* @private
*/
static _objectMapped (params = {}, fieldItem, options) {
const { item = '', path, ops, schema = {}, index = null, isArray = false } = params
map(item, (value, field) => {
const newPath = `${path}.${field}`
if (typeof value === 'object') {
return DiffHelper._objectMapped({ path: newPath, item: value, ops, schema, index, isArray }, fieldItem, options)
}
const change = { from: '', to: '' }
const label = DiffHelper._getLabel(newPath, schema)
change[`${fieldItem}`] = value
changes.push(DiffHelper._changeTransformToView({ ...change, path: newPath, ops, label, index, isArray }, options))
})
}
/**
* @author Welington Monteiro
* @param { String } str - string name to capitalize
* @return {string} name field capitalized
* @private
*/
static _capitalizedKey (str = '') {
return startCase(camelCase(str))
}
/**
* @author Welington Monteiro
* @param { String } path - path object
* @param { Object } schema - paths schema mapped
* @return { string } return result
* @private
*/
static _getLabel (path = '', schema = {}) {
const paths = compact(path.replace(/[0-9]/ig, '').split('.'))
const lastPath = paths[paths.length - 1]
const label = DiffHelper._getCustomLabel(paths, schema)
const nameCapitalized = DiffHelper._capitalizedKey(lastPath)
return (label || nameCapitalized)
}
/**
* @author Welington Monteiro
* @param { Array } pathsArray - flatten paths schema
* @param { Object } schema - Schemas mapped paths
* @return {string} customLabel - return name custom label
*/
static _getCustomLabel (pathsArray = [], schema = {}) {
const flattenPath = pathsArray.join('.')
const paths = !isEmpty(schema.paths) ? schema.paths[flattenPath] : ''
const singleNestedPaths = !isEmpty(schema.singleNestedPaths) ? schema.singleNestedPaths[flattenPath] : ''
const subpaths = !isEmpty(schema.subpaths) ? schema.subpaths[flattenPath] : ''
return get(paths, 'options._label_', get(singleNestedPaths, 'options._label_', get(subpaths, 'options._label_')))
}
/**
* @author Welington Monteiro
* @description Omitted field if not mapped on dicionary
* @param { String } path - Item mapped
* @param { Object } flatDictionary - Dictionary flatten
* @return { Boolean } isOmitted - Returns item
* @param { Object } [options] - options change transform to view
* @private
*/
static _omittedFieldsIfNotMapped (path, flatDictionary, options) {
if (isEmpty(flatDictionary)) return false
const isStrict = get(options, 'isStrict', true)
let isOmitted = false
const isMapped = !!DiffHelper.getPathNameMapped(path, flatDictionary)
if (!isMapped && isStrict) isOmitted = true
return isOmitted
}
/**
* @author Welington Monteiro
* @description Replace index number for place holder
* @param { String } path - Path item
* @param flatDictionary
* @return {*}
* @private
*/
static getPathNameMapped (path, flatDictionary = {}) {
const pathReplaced = DiffHelper.replaceIndexWithPlaceholder(path)
const pathLabelName = DiffHelper.getLabelOrKeyName(pathReplaced, '_label_')
const pathKeyName = DiffHelper.getLabelOrKeyName(pathReplaced, '_key_')
const pathWithLabelName = get(flatDictionary, `${pathLabelName}`)
const pathWithKeyName = get(flatDictionary, `${pathKeyName}`)
const pathWithArrayName = get(flatDictionary, `${pathReplaced}`)
return (pathWithLabelName || pathWithKeyName || pathWithArrayName)
}
/**
* @author Welington Monteiro
* @param { String } path - Path item
* @return {*}
* @private
*/
static replaceIndexWithPlaceholder (path) {
path = path.replace(/(\.)([0-9]+)(\.)/g, '._array_.')
path = path.replace(/(\.)([0-9]+)/g, '._array_')
return path
}
/**
* @author Welington Monteiro
* @param { String } pathReplaced - Path with place holder _array_ item
* @param { String } key - Key name: _key_ , _label_
* @return {string}
*/
static getLabelOrKeyName (pathReplaced, key = '_label_') {
let paths = pathReplaced.split('.')
const lastPath = paths.pop()
if (includes(['_array_'], lastPath)) {
paths.push(lastPath)
}
if (includes(['_label_', '_key_'], lastPath)) {
paths.push(lastPath)
}
paths.push(key)
paths = paths.join('.')
return paths
}
}
module.exports = DiffHelper
|