All files plugin.js

97.73% Statements 129/132
86.96% Branches 40/46
100% Functions 32/32
99.21% Lines 125/126

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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419  1x 1x 1x 1x 1x                                                                               44x 5x 1x 1x   4x               44x 8x             44x 4x     44x 28x     44x 11x     44x 1x     44x 45x     44x 1x     44x 4x     44x 4x                     98x 98x 98x 98x 98x                     94x 94x                   98x 98x 1x   98x                         397x 130x                 81x           81x 81x 81x                 81x 81x 81x   81x 5x 5x   76x 15x 15x   61x 61x 61x                     8x 8x   8x                       81x 81x   81x 81x 81x 81x 81x 81x   81x 28x   81x 38x   81x 11x   81x 81x                   28x 28x 28x 28x   28x 28x                   11x   11x 11x 11x 11x 11x   11x 11x   11x                     38x 6x   38x 32x   38x                     4x       4x   4x 4x   4x                 46x 46x   46x                   6x                 1x 1x   1x                       11x   11x 11x   11x                       28x   28x 28x   28x                         6x   6x 6x   6x                         32x   32x 32x   32x     1x  
'use strict'
const Promise = require('bluebird')
const { HistoryLogModel } = require('./model')
const DeepDiff = require('./diffHelper')
const { isEmpty, get, assign, pick, set, result: execute } = require('lodash')
let mongooseConnection = null
 
/**
 *
 * @param { mongoose } schema - schema mongoose
 * @param { Object } options
 * @example {
 *   userPaths: []                              //name paths user to saved on logs
 *   isAuthenticate: true                       //default is true
 *   customCollectionName: String               //default is collection name
 *   connectionUri: String                      //default is connection of collection
 *   moduleName: String                         //default is collection name
 *   indexes: [
 *        {'path': 1},                          //paths create index on history log collection
 *        {'path': -1},
 *        {'path': 'text'}
 *   ]
 *   omitPaths: ['_id', '__v']                  //paths omit on created history log
 *   addCollectionPaths: [                      //add paths in collection history log
 *      {key: 'path1', value: 'String' },       //    key - name path
 *      {key: 'path2', value: 'String' },       //    value - mongoose types .('ObjectId', 'Mixed', 'String', 'Number', etc)
 *      {key: 'path3.path2',                    //    sudoc : {key: 'field.subdoc', value: 'String'}
 *          value: 'ObjectId' },
 *   ],
 *   changeTransform: {
 *     to: 'newPathToView'                      //new value to path 'to' transform to view
 *     from: 'newPathToView'                    //new value to path 'from' transform to view
 *     label: 'newPathToView'                   //new value to path 'label' transform to view
 *     ops: 'newPathToView'                     //new value to path 'ops' transform to view
 *     path: 'newPathToView'                    //new value to path 'path' transform to view
 *   }
 *
 * }
 */
function HistoryPlugin (schema, options = {}) {
  /**
   * @author Welington Monteiro
   * @param { Object } loggedUser - Logged user from request
   * Model.addLoggedUser(user)
   */
  schema.statics.addLoggedUser = function (loggedUser) {
    if (!loggedUser) {
      console.error('MONGOOSE-HISTORY-TRACE::addLoggedUser - loggedUser params is required. \nExample: Model.addLoggedUser(currentUser)')
      return
    }
    set(schema, '_loggedUser', loggedUser)
  }
  /**
   * @author welington Monteiro
   * @param { Object } [old] - old state json object
   * @param { Object } [current] - current state json object
   * @return {Array} changes -  return array changes diffs
   */
  schema.statics.getChangeDiffs = async function (old, current) {
    return _processGetDiffs.call(this, { old, current }, options)
  }
 
  /**
   * @author Welington Monteiro
   * @param { Object } params
   */
  schema.statics.createHistory = async function (params) {
    await _processCreateHistory.call(getCurrentUser.call(this, schema, params), params, options)
  }
 
  schema.pre('save', async function () {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processPreSave, options)
  })
 
  schema.pre(/update|updateOne|findOneAndUpdate|findByIdAndUpdate|updateMany|findOneAndReplace|replaceOne/, async function () {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processPreUpdate, options)
  })
 
  schema.pre(/deleteOne|remove/, async function () {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processPreRemove, options)
  })
 
  schema.pre(/deleteMany/, async function () {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processRemoveMany, options)
  })
 
  schema.pre(/remove/, { document: false, query: true }, async function () {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processRemoveMany, options)
  })
 
  schema.post(/findOneAndRemove|findByIdAndRemove|findByIdAndDelete|findOneAndDelete/, async function (doc) {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processPosRemove, options, doc)
  })
 
  schema.post('insertMany', async function (docs) {
    await initializeProcess.call(getCurrentUser.call(this, schema), _processPosInsertMany, options, docs)
  })
}
 
/**
 * @author Welington Monteiro
 * @param { Schema } schema - mongoose Schema
 * @param params
 * @return {getCurrentUser} - return this context with logged user
 */
function getCurrentUser (schema, params) {
  const _loggedUser = get(schema, '_loggedUser', {})
  const loggedUser = get(params, 'loggedUser', {})
  this._loggedUser = _toJSON(!isEmpty(_loggedUser) ? _loggedUser : loggedUser)
  delete schema._loggedUser
  return this
}
 
/**
 * @author Welington Monteiro
 * @param { function } method - method call to process
 * @param { Object } options - params configuration before saved log
 * @param {Array | Object } docs - data document
 * @return {Promise<void>}
 */
async function initializeProcess (method, options, docs) {
  _setConnection(options)
  await method.call(this, options, docs)
}
 
/**
 * @description set mongoose connection
 * @author Welington Monteiro
 * @param { Object } options - params configuration before saved log
 * @private
 */
function _setConnection (options) {
  const conn = get(options, 'mongooseConnection')
  if ((!mongooseConnection || isEmpty(mongooseConnection)) && (conn || !isEmpty(conn))) {
    mongooseConnection = get(conn, 'connection', conn)
  }
  Iif (!mongooseConnection || isEmpty(mongooseConnection)) {
    console.error('MONGOOSE-HISTORY-TRACE: mongooseConnection options is required. \nExample: Model.plugin(mongooseHistoryTrace, {mongooseConnection: conn}')
  }
}
 
/**
 * @author Welington Monteiro
 * @param { Object } json - object transform
 * @param { Boolean } [isArray] - is Array return
 * @return {Object} return object to json
 * @private
 */
function _toJSON (json, isArray) {
  if (isEmpty(json)) { return isArray === true ? [] : {} }
  return JSON.parse(JSON.stringify(json))
}
 
/**
 * @author Welington Monteiro
 * @param {Object} doc - doc
 * @return {{method: *, documentNumber: *, module: *, changes: *, loggedUser: *, action: *}}
 */
function _mappedFieldsLog (doc = {}) {
  const actions = {
    updated: 'Edited Document',
    deleted: 'Removed Document',
    created: 'Created Document',
    undefined: 'No Defined'
  }
  const { changes, module, documentNumber, method, user } = doc
  const action = get(actions, `${method}`, method)
  return { changes, action, module, documentNumber, method, user }
}
 
/**
 *@author Welington Monteiro
 * @param { Object } object - object mapped to saved
 * @param { Object } options - params configuration before saved log
 */
async function _saveHistoryLog (object, options) {
  const hasUsers = !isEmpty(get(object, 'user'))
  const isAuthenticated = get(options, 'isAuthenticated')
  const hasChanges = !isEmpty(get(object, 'changes'))
 
  if (!hasChanges) {
    console.warn('MONGOOSE-HISTORY-TRACE: path: {changes} no diffs documents.')
    return
  }
  if (!hasUsers && isAuthenticated) {
    console.warn('MONGOOSE-HISTORY-TRACE: path: {user} is required. Example: Model.addLoggedUser(req.user)')
    return
  }
  const HistoryLog = HistoryLogModel(mongooseConnection, options)
  const history = new HistoryLog(object)
  return await history.save()
}
 
/**
 * @author Welington Monteiro
 * @param { object } params
 * @param { Object } options - params configuration options plugin
 * @return {Array}
 * @private
 */
async function _processGetDiffs (params, options) {
  const old = get(params, 'old', {})
  const current = get(params, 'current', {})
 
  return DeepDiff.getDiff({ old, current }, {}, options)
}
 
/**
 * @author Welington Monteiro
 * @param { Object } options - params configuration options plugin
 * @param { Object } [params] - params paths to save history
 * @param { Object } [doc] - object to save
 * @param { String } method - name of method to save
 * @return { Object } - return object mounted to save
 */
async function mountDocToSave ({ options, params, doc }, method) {
  const self = this
  let result = {}
 
  set(result, 'old', _toJSON(get(params, 'old', {})))
  set(result, 'current', _toJSON(get(params, 'current', {})))
  set(result, 'schema', get(self, 'schema'))
  set(result, 'user', pick(get(self, '_loggedUser'), get(options, 'userPaths', [])))
  set(result, 'module', get(options, 'moduleName', get(self, 'mongooseCollection.name', get(self, 'collection.name'))))
  set(result, 'method', (method || get(params, 'method', 'undefined')))
 
  if ({}.hasOwnProperty.call(self, 'isNew')) {
    result = await _helperPreSave.call(this, result)
  }
  if (!isEmpty(doc)) {
    result = _helperPosSaveWithDoc.call(this, result, doc)
  }
  if (method === 'updated') {
    result = await _helperPreUpdate.call(this, result)
  }
  set(result, 'documentNumber', get(result, 'old._id', get(result, 'current._id')))
  return result
}
 
/**
 * @author Welington Monteiro
 * @param { Object } result - result Object mount paths to save
 * @return { Object } - return object mount
 * @private
 */
async function _helperPreSave (result) {
  const self = this
  set(result, 'method', (get(self, 'isNew') ? 'created' : 'updated'))
  set(result, 'current', _toJSON(execute(self, 'toObject', self)))
  const _id = get(result, 'current._id')
 
  if (!self.isNew) { set(result, 'old', _toJSON(await self.constructor.findOne({ _id }))) }
  return result
}
 
/**
 * @author Welington Monteiro
 * @param { Object } result - result Object mount paths to save
 * @return { Object } - return object mount
 * @private
 */
async function _helperPreUpdate (result) {
  const self = this
 
  const query = get(self, '_conditions')
  Iif (isEmpty(query)) { return console.warn(`Not found documents to ${result.method} history logs.`) }
  const old = _toJSON(await self.findOne(query))
  Iif (isEmpty(old)) { return console.warn(`Not found documents to ${result.method} history logs.`) }
  const mod = _toJSON(get(self, '_update.$set', get(self, '_update')))
 
  set(result, 'old', old)
  set(result, 'current', assign({}, old, DeepDiff.unFlattenJson(mod)))
 
  return result
}
 
/**
 *
 * @param { Object } result - result Object mount paths to save
 * @param { Object } doc - object to save
 * @return { Object } - return object mount
 * @private
 */
function _helperPosSaveWithDoc (result, doc) {
  if (result.method === 'created') {
    set(result, 'current', _toJSON(execute(doc, 'toObject', doc)))
  }
  if (result.method === 'deleted') {
    set(result, 'old', _toJSON((execute(doc, 'toObject', doc))))
  }
  return result
}
 
/**
 * @author Welington Monteiro
 * @param { Object } params - params to save history manually
 * @param { Object } options - params configuration before saved log
 * @return {Promise<void>}
 * @private
 */
async function _processCreateHistory (params, options) {
  _setConnection(options)
  const {
    schema, user, module, method,
    old, current, documentNumber
  } = await mountDocToSave.call(this, { options, params })
 
  const changes = DeepDiff.getDiff({ old, current }, schema, options)
  const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
 
  await _saveHistoryLog(docMapped, options)
}
 
/**
 * @author Welington Monteiro
 * @param { Object } options - params configuration before saved log
 * @private
 */
async function _processRemoveMany (options) {
  const query = get(this, '_conditions')
  const olds = _toJSON(await this.find(query), true)
 
  Promise.map(olds, async (eachOld) => await _processPosRemove.call(this, options, eachOld))
}
 
/**
 * @author Welington Monteiro
 * @param { Array } docs - List of document inserted
 * @param { Object } options - params configuration before saved log
 * @private
 */
async function _processPosInsertMany (options, docs) {
  return Promise.map(docs, async (eachDoc) => await _processPosSave.call(this, options, eachDoc))
}
 
/**
 * @author Welington Monteiro
 * @param { Object } options - params configuration before saved log
 * @private
 */
async function _processPreRemove (options) {
  const query = get(this, '_conditions')
  const old = _toJSON(await this.findOne(query))
 
  await _processPosRemove.call(this, options, old)
}
 
/**
 * @author Welington Monteiro
 * @param { Object } options - params configuration before saved log
 * @return {Promise<*>}
 */
async function _processPreUpdate (options) {
  const {
    schema, user, module, method,
    old, current, documentNumber
  } = await mountDocToSave.call(this, { options }, 'updated')
 
  const changes = DeepDiff.getDiff({ old, current }, schema, options)
  const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
 
  await _saveHistoryLog(docMapped, options)
}
 
/**
 * @author Welington Monteiro
 * @param { Object } options - params configuration before saved log
 * @private
 */
async function _processPreSave (options) {
  const {
    schema, user, module, method,
    old, current, documentNumber
  } = await mountDocToSave.call(this, { options })
 
  const changes = DeepDiff.getDiff({ old, current }, schema, options)
  const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
 
  await _saveHistoryLog(docMapped, options)
}
 
/**
 * @author Welington Monteiro
 * @param doc
 * @param { Object } options - params configuration before saved log
 * @private
 */
async function _processPosSave (options, doc) {
  const {
    schema, user, module, method,
    current, documentNumber
  } = await mountDocToSave.call(this, { options, doc }, 'created')
 
  const changes = DeepDiff.getDiff({ current }, schema, options)
  const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
 
  await _saveHistoryLog(docMapped, options)
}
 
/**
 * @author Welington Monteiro
 * @param { Object } doc - object mapped
 * @param { Object } options - params configuration before saved log
 * @return {Promise<void>}
 */
async function _processPosRemove (options, doc) {
  const {
    schema, user, module,
    method, old, documentNumber
  } = await mountDocToSave.call(this, { options, doc }, 'deleted')
 
  const changes = DeepDiff.getDiff({ old }, schema, options)
  const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
 
  await _saveHistoryLog(docMapped, options)
}
 
module.exports = HistoryPlugin