all files / app/bin/static/lib/ gridFsStorage.js

85.71% Statements 18/21
75% Branches 3/4
85.71% Functions 6/7
90% Lines 18/20
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                                                    
var mongoose = require('mongoose')
var path = require('path')
 
function getDestination (req, file, cb) {
  cb(null, path.join(req.path, file.fieldname, file.originalname))
}
 
function GridFsStorage (opts) {
  this.getDestination = (opts.destination || getDestination)
}
 
GridFsStorage.prototype._handleFile = function _handleFile (req, file, cb) {
  // normal options, plus we getDestination to supply (optional) id
  this.getDestination(req, file, function (err, path, id) {
    Iif (err) return cb(err)
    var gfs = mongoose.gridFs
    var writestream = gfs.createWriteStream({
      _id: id,
      filename: path,
      content_type: file.mimetype
    })
    file.stream.pipe(writestream)
    writestream.on('error', cb)
    writestream.on('finish', function () {
      cb(null, {
        path: path,
        id: writestream.id,
        size: writestream.bytesWritten
      })
    })
  })
}
 
GridFsStorage.prototype._removeFile = function _removeFile (req, file, cb) {
  var gfs = mongoose.gridFs
  gfs.remove({
    filename: file.path
  }, cb)
}
 
module.exports = function (opts) {
  return new GridFsStorage(opts)
}