1

I need to get the files and the fields that come on a POST request from a multipart/form-data, firebase functions don't always have expressjs and it takes time to migrate the current functions; also I found using a middleware as Multer without express really complex.

I had to look up for another solution that allowed me to get the files and fields from a multipart/form-data with out using express.

Danny Fallas
  • 628
  • 1
  • 5
  • 11

1 Answers1

1

The solution I came up with is to use the busboy npm module on a Promise to be able to parse this request on to files and fields. By default firebase functions recieve the multipart-form request data as a buffer on request.body and this is what makes it possible to parse.

// util.js
const Busboy = require('busboy');

const parse = (headers, buffer) => {
    return new Promise((resolve, reject) => {
        const busboy = new Busboy({ headers: headers });

        let files = {};
        let fields = {};

        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            file.on('data', function (data) {
                files[fieldname] = data;
            });
        }).on('field', function (fieldname, val) {
            fields[fieldname] = val;
        }).on('finish', function () {
            resolve({ files, fields });
        });

        busboy.end(buffer);
    });
};

module.exports = {
    parse
};


// api.js
exports.upload = functions.https.onRequest(async (request, response) => {
    const { files, fields } = await parse(request.headers, request.body);
    ...
};

This way I was able to get what I needed without using express and without having to create a way to make express middlewares like multer work onRequest.

If you have another way please share as this is the solution I came up, but it's not necessarily the best.

D.

Danny Fallas
  • 628
  • 1
  • 5
  • 11