Guest User

Untitled

a guest
Feb 16th, 2016
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * MongooseJS plugin to create Asset revisions
  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 RevisionInit'})
  11. const accountHelper = appRoot.require('./dist/lib/helpers/account')
  12. const _m            = appRoot.require('./dist/lib/helpers/mongoose-helper')( Mongoose )
  13.  
  14. module.exports = ( schema, options ) => {
  15.     // Middleware for any update-type queries
  16.     _.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => {
  17.         // Increment the Mongoose (__v)ersion for any updates
  18.         schema.pre( query, function( next ) {
  19.             this.increment()
  20.             next()
  21.         })
  22.  
  23.         // Create revisions for each asset update
  24.         schema.post( query, assetData => {
  25.             let partitionId
  26.  
  27.             // Verify the asset ID was provided..
  28.             if( _m.isObjectId( assetData._id ) === false ){
  29.                 log.error('Failed to create revision - No asset ID found')
  30.                 return
  31.             }
  32.  
  33.             // Verify the partition ID was provided (either populated or not)
  34.             if( _m.isObjectId( assetData._partition ) === true ){
  35.                 partitionId = assetData._partition
  36.             }
  37.             else if( _m.isObjectId( assetData._partition._id ) === true ){
  38.                 partitionId = assetData._partition._id
  39.             }
  40.             else {
  41.                 log.error(`Failed to create revision for the asset ID ${assetData._id.toString()} - No partition ID found`)
  42.                 return
  43.             }
  44.  
  45.             const assetMeta = {
  46.                 assetId:    assetData._id.toString(),
  47.                 partitionId: partitionId,
  48.                 revision: assetData.__v
  49.             }
  50.  
  51.             Mongoose.models.Revision.createRevision( assetMeta, assetData )
  52.                 .then( revision => log.info(`Revision # ${revision.revision} created (ID: ${revision._id.toString()}) for asset ID ${assetData._id.toString()}`))
  53.                 .catch( err => log.error(`Failed to create revision for asset ID ${assetData._id.toString()} - ${err}`))
  54.         })
  55.     })
  56. }
Add Comment
Please, Sign In to add comment