Advertisement
Guest User

Untitled

a guest
Feb 16th, 2016
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * MongooseJS plugin to auto-populate the _createdBy and _updatedBy document values (If they exist in the schema)
  3.  */
  4. 'use strict'
  5.  
  6. import _ from 'moar-lodash'
  7. import * as appRoot from 'app-root-path'
  8. import Mongoose from 'mongoose'
  9.  
  10. const log           = appRoot.require('./dist/lib/utils/logger')({ plugin: 'Mongoose ByAccount'})
  11. const accountHelper = appRoot.require('./dist/lib/helpers/account')
  12.  
  13. module.exports = ( schema, options ) => {
  14.     schema.pre( 'save', function( next ) {
  15.         // Only continue if the schema has createdBy or updatedBy
  16.         if( _.isObject( schema.paths._createdBy ) || _.isObject( schema.paths._updatedBy ) ) {
  17.             // Retrieve the account ID and username
  18.             const accountId = accountHelper.getAccount( '_id' )
  19.             const accountUn = accountHelper.getAccount( 'username' ) || 'Unknown'
  20.  
  21.             // If no account ID is found, then just return void, to avoid updating the updated/created by
  22.             if( ! accountId ) {
  23.                 log.warn( `Unable to populate _createdBy - No account ID set in the Account Helper` )
  24.             }
  25.  
  26.             // If Mongooses isNew value is true then its being created
  27.             else if( this.isNew ) {
  28.                 if( _.isObject( schema.paths._createdBy ) ) {
  29.                     log.debug( `Schema item _createdBy found - Populating with ${accountId} (Username: ${accountUn})` )
  30.                     this._createdBy = accountId
  31.                     this.markModified( '_createdBy' )
  32.                 }
  33.                 else {
  34.                     log.debug( `Document is being created, but no _createdBy object found in schema` )
  35.                 }
  36.             }
  37.  
  38.             // No isNew value, so its being updated
  39.             else {
  40.                 if( _.isObject( schema.paths._updatedBy ) ) {
  41.                     log.debug( `Schema item _updatedBy found - Populating with ${accountId} (Username: ${accountUn})` )
  42.                     this._updatedBy = accountId
  43.                     this.markModified( '_updatedBy' )
  44.                 }
  45.                 else {
  46.                     log.debug( `Document is being updated, but no _updatedBy object found in schema` )
  47.                 }
  48.             }
  49.         }
  50.         next()
  51.     } )
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement