const fs = require('fs');
const Formidable = require('formidable');
const FormData = require('form-data');

module.exports = (uploadConfig = {}) => (req, res, next) => {
    if (!req.is('multipart')) {
        next();

        return;
    }

    let form = new Formidable(uploadConfig);

    form.parse(req, (err, fields, files) => {
        if (err) {
            next(err);

            return;
        }

        let body = new FormData();

        Object.entries(fields)
            .forEach(([k, v]) => body.append(k, v));

        Object.entries(files)
            .forEach(([k, file]) => {
                body.append(k, fs.createReadStream(file.path), {
                    contentType: file.type,
                    knownLength: file.size,
                });
            });

        req.body = body;
        req.files = files;
        req.boundary = body.getBoundary();

        next();
    });
};
