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 | 1x 1x 1x 1x 1x 1x 58x 58x 58x 8x 58x 3x 58x 23x 23x 23x 58x 11x 11x 11x 58x 1x 1x 1x 58x 1x 1x 1x 58x 1x 1x 1x 58x 4x 4x 4x 58x 4x 4x 4x 114x 69x 46x 46x 46x 46x 1x 1x 45x 7x 7x 38x 38x 38x 8x 8x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 11x 11x 11x 11x 11x 11x 11x 11x 7x 7x 7x 7x 2x 2x 2x 6x 1x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 21x 23x 2x 2x 23x 23x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x | 'use strict'
const Promise = require('bluebird')
const { HistoryLogModel } = require('./model')
const DeepDiff = require('./diffHelper')
const { isEmpty, get, assign, pick } = require('lodash')
const ACTIONS = {
updated: 'Edited Document',
deleted: 'Removed Document',
created: 'Created Document',
undefined: 'No Defined'
}
let _loggedUser = {}
/**
*
* @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
*/
schema.statics.addLoggedUser = function (loggedUser) {
_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(this, params, options)
}
schema.pre('save', async function () {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processPreSave.call(this, options)
})
schema.pre(/update|updateOne|findOneAndUpdate|findByIdAndUpdate|updateMany|findOneAndReplace|replaceOne/, async function () {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processPreUpdate.call(this, options)
})
schema.pre(/deleteOne|remove/, async function () {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processPreRemove.call(this, options)
})
schema.pre(/deleteMany/, async function () {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processRemoveMany.call(this, options)
})
schema.pre(/remove/, { document: false, query: true }, async function () {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processRemoveMany.call(this, options)
})
schema.post(/findOneAndRemove|findByIdAndRemove|findByIdAndDelete|findOneAndDelete/, async function (doc) {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processPosRemove.call(this, doc, options)
})
schema.post('insertMany', async function (docs) {
this._loggedUser = _toJSON(_loggedUser)
_loggedUser = {}
await _processPosInsertMany.call(this, docs, options)
})
}
/**
* @author Welington Monteiro
* @param { Object } json - object transform
* @return {Object} return object to json
* @private
*/
function _toJSON (json) {
if (isEmpty(json)) return {}
return JSON.parse(JSON.stringify(json))
}
/**
* @author Welington Monteiro
* @param {Object} doc - doc
* @return {{method: *, documentNumber: *, module: *, changes: *, loggedUser: *, action: *}}
*/
function _mappedFieldsLog (doc = {}) {
const { changes, module, documentNumber, method, user } = doc
const action = ACTIONS[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) {
if (isEmpty(get(object, 'changes'))) {
console.warn('MONGOOSE-HISTORY-TRACE: path: {changes} no diffs documents.')
return
}
if (isEmpty(get(object, 'user')) && get(options, 'isAuthenticated', true)) {
console.warn('MONGOOSE-HISTORY-TRACE: path: {user} is required. Example: Model.addLoggedUser(req.user)')
return
}
const HistoryLog = HistoryLogModel(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 = {}, current = {} } = params
return DeepDiff.getDiff({ old, current }, {}, options)
}
/**
* @author Welington Monteiro
* @param { Object } params
* @param { Object } options - params configuration before saved log
* @return {Promise<void>}
* @private
*/
async function _processCreateHistory (params, options) {
const old = _toJSON(get(params, 'old', {}))
const current = _toJSON(get(params, 'current', {}))
const schema = get(this, 'schema')
const user = pick(get(params, 'loggedUser'), get(options, 'userPaths', []))
const module = get(options, 'moduleName', get(this, 'mongooseCollection.name', get(this, 'collection.name')))
const documentNumber = get(old, '_id')
const method = get(params, 'method', 'undefined')
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
* @return {Promise<*>}
*/
async function _processPreUpdate (options) {
const query = get(this, '_conditions')
const schema = get(this, 'schema')
const user = pick(get(this, '_loggedUser'), get(options, 'userPaths', []))
const old = _toJSON(await this.findOne(query))
const module = get(options, 'moduleName', get(this, 'mongooseCollection.name'))
const mod = _toJSON(get(this, '_update.$set', get(this, '_update')))
const documentNumber = get(old, '_id')
const method = 'updated'
if (isEmpty(old) || isEmpty(query)) return console.warn(`Not found documents to ${method} history logs.`)
const current = assign({}, old, mod)
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))
Promise.map(olds, async (eachOld) => await _processPosRemove.call(this, eachOld, options))
}
/**
* @author Welington Monteiro
* @param { Array } docs - List of document inserted
* @param { Object } options - params configuration before saved log
* @private
*/
async function _processPosInsertMany (docs, options) {
return Promise.map(docs, async (eachDoc) => await _processPosSave.call(this, eachDoc, options))
}
/**
* @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, old, options)
}
/**
* @author Welington Monteiro
* @param { Object } options - params configuration before saved log
* @private
*/
async function _processPreSave (options) {
const module = get(options, 'moduleName', get(this, 'collection.name'))
const schema = get(this, 'schema')
const method = get(this, 'isNew') ? 'created' : 'updated'
const user = pick(get(this, '_loggedUser'), get(options, 'userPaths', []))
const current = _toJSON(this.toObject())
const documentNumber = get(current, '_id')
let changes = []
if (this.isNew) {
changes = DeepDiff.getDiff({ current }, schema, options)
}
if (!this.isNew) {
const old = _toJSON(await this.constructor.findOne({ _id: documentNumber }))
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 (doc, options) {
const module = get(options, 'moduleName', get(this, 'collection.name'))
const schema = get(this, 'schema')
const method = 'created'
const user = pick(get(this, '_loggedUser'), get(options, 'userPaths', []))
const current = _toJSON(doc.toObject())
const documentNumber = get(current, '_id')
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 (doc, options) {
const old = _toJSON((doc.toObject ? doc.toObject() : doc))
const schema = get(this, 'schema')
const module = get(options, 'moduleName', get(this, 'mongooseCollection.name', get(this, 'collection.name')))
const user = pick(get(this, '_loggedUser'), get(options, 'userPaths', []))
const method = 'deleted'
const documentNumber = get(old, '_id')
const changes = DeepDiff.getDiff({ old }, schema, options)
const docMapped = _mappedFieldsLog({ changes, method, module, documentNumber, user })
await _saveHistoryLog(docMapped, options)
}
module.exports = HistoryPlugin
|