Node.js 在上传文件之前,快速Multer验证请求

Node.js 在上传文件之前,快速Multer验证请求,node.js,express,multer,multer-s3,Node.js,Express,Multer,Multer S3,我目前正在使用multer-s3()将单个csv文件上载到s3,我的工作方式如下: 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:

我目前正在使用multer-s3()将单个csv文件上载到s3,我的工作方式如下:

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())
    }
  })
});
然后它的路线是这样的:

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;

  });

我的问题是,在Multer将我的文件上传到S3之前,我如何验证请求对象。

您可以在上传之前链接多个中间件,然后在那里检查令牌

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;

  });

只是另一个验证层。您可以使用Joi来验证您的请求。在保存数据之前

//router.ts
router.post('/', Upload.single('image'), ProductController.create);

//controller.ts
export const create = async(req:Request,res:Response) => {

   const image = (req.file as any).location;
   const body = { ...req.body, image: image }

   const { error } = validate(body);
   if (error) return res.status(400).send(error.details[0].message);

   const product = await ProductService.create(body);

   res.status(201).send(product); 
}

//product.ts 
function validateProduct(product : object) {
  const schema = Joi.object({
      name: Joi.string().min(5).max(50).required(),
      brand: Joi.string().min(5).max(50).required(),
      image: Joi.string().required(),
      price: Joi.number().required(),
      quantity:Joi.number(),
      description: Joi.string(),
  });

  return schema.validate(product);  
}