Search code examples
javascriptnode.jsexpressmiddleware

Node: send data from middlware to function


I'm using express and I need to create some middleware which is for validation and

I’ve something like

Code:

app.use(‘/upload', fromData)
app.use(‘/upload', function firstUpload(req, res, next) {
    return fileHandler(req, res, next)
        .then((status) => {
            res.statusCode = 201;
            res.end(status)
        }).catch((err) => {
            return next(new appError(500, err));
        });
});

Now I use another function fromHandler

function formData(req) {

 return new Promise((resolve, reject) => {
 const form = new formidable.IncomingForm();
  form.maxFileSize = 100 * 1024 * 1024;
  form.keepExtensions = true;
  form.multiEntry = true;
  form.parse(req, (err, fields, files) => {
    const filesInfo = Object.keys(files).map((key) => {
        const file = files[key];
        const filePath = file.path;
        const fileExt = path.extname(file.name);
        const fileName = path.basename(file.name, fileExt);
        return {filePath, fileExt};
    });
 }
  Resolve(filesInfo)
}

What I need is to return the data Resolve(filesInfo) from the formData function to The fileHandler function, how can I do it? The fileHandler function need to get the filesInfo


Solution

  • You don't need a promise here. middleware use next function as the callback to go to next handler. Before it, you should put data from the middleware into req object. After that, you can use by getting from req. filesInfo.

    function formData(req, res, next) {
      const form = new formidable.IncomingForm();
      form.maxFileSize = 100 * 1024 * 1024;
      form.keepExtensions = true;
      form.multiEntry = true;
      form.parse(req, (err, fields, files) => {
        if (err || fields.length === 0) {
           res.status(500).json({ message: 'you are done' }); // <- this is where you stop the request with an error.
        }
        const filesInfo = Object.keys(files).map((key) => {
            const file = files[key];
            const filePath = file.path;
            const fileExt = path.extname(file.name);
            const fileName = path.basename(file.name, fileExt);
            return {filePath, fileExt};
        });
        req.filesInfo = filesInfo;
        next();
      }
    }
    
    function fileHandler(req, res) {
      console.log(req.filesInfo); /* <- you can also get the filesInfo here */ 
      return Promise.resolve({});
    }
    
    app.use(‘/upload', fromData)
    app.use(‘/upload', function(req, res, next) {
        // console.log(req.filesInfo); => You can get your filesInfo here and do whatever you want
        return fileHandler(req, res, next)
            .then((status) => {
                res.statusCode = 201;
                res.end(status)
            }).catch((err) => {
                return next(new appError(500, err));
            });
    });