node.jsexpressmultermulter-s3

Express Multer validate request before uploading file


I am currently using multer-s3 (https://www.npmjs.com/package/multer-s3) to upload a single csv file to S3, i have it working this way:

var multer = require('multer');
var multerS3 = require('multer-s3');
var AWS = require('aws-sdk');

AWS.config.loadFromPath(...);
var s3 = new AWS.S3(...);

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'my-bucket',
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
});

then it's routed like this:

app.route('/s3upload')
  .post(upload.single('data'), function(req, res) {

    // at this point the file is already uploaded to S3 
    // and I need to validate the token in the request.

    let s3Key = req.file.key;

  });

My question is, how can I validate the request object before Multer uploads my file to S3.


Solution

  • You can just chain one more middleware before the upload and then can check the token there

    function checkToken(req, res) {
        // Logic to validate token
    }
    
    app.route('/s3upload')
      .post(checkToken, upload.single('data'), function(req, res) {
    
        // at this point the file is already uploaded to S3 
        // and I need to validate the token in the request.
    
        let s3Key = req.file.key;
    
      });