Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * MongooseJS plugin to create Asset revisions
- */
- 'use strict'
- import _ from 'moar-lodash'
- import * as appRoot from 'app-root-path'
- import Mongoose from 'mongoose'
- const log = appRoot.require('./dist/lib/utils/logger')({ plugin: 'Mongoose RevisionInit'})
- const accountHelper = appRoot.require('./dist/lib/helpers/account')
- const _m = appRoot.require('./dist/lib/helpers/mongoose-helper')( Mongoose )
- module.exports = ( schema, options ) => {
- // Middleware for any update-type queries
- _.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => {
- // Increment the Mongoose (__v)ersion for any updates
- schema.pre( query, function( next ) {
- this.increment()
- next()
- })
- // Create revisions for each asset update
- schema.post( query, assetData => {
- let partitionId
- // Verify the asset ID was provided..
- if( _m.isObjectId( assetData._id ) === false ){
- log.error('Failed to create revision - No asset ID found')
- return
- }
- // Verify the partition ID was provided (either populated or not)
- if( _m.isObjectId( assetData._partition ) === true ){
- partitionId = assetData._partition
- }
- else if( _m.isObjectId( assetData._partition._id ) === true ){
- partitionId = assetData._partition._id
- }
- else {
- log.error(`Failed to create revision for the asset ID ${assetData._id.toString()} - No partition ID found`)
- return
- }
- const assetMeta = {
- assetId: assetData._id.toString(),
- partitionId: partitionId,
- revision: assetData.__v
- }
- Mongoose.models.Revision.createRevision( assetMeta, assetData )
- .then( revision => log.info(`Revision # ${revision.revision} created (ID: ${revision._id.toString()}) for asset ID ${assetData._id.toString()}`))
- .catch( err => log.error(`Failed to create revision for asset ID ${assetData._id.toString()} - ${err}`))
- })
- })
- }
Add Comment
Please, Sign In to add comment