import express from 'express';

function _mime(req) {
  const str = req.headers['content-type'] || '';
  return str.split(';')[0];
}

export default function (options, forceContentType = true) {
    const json = express.json(options);

    return function (req, res, next) {
        // optionally enforce json body type. without this the json middleware will skip parsing and req.body might be undefined
        if (_mime(req) !== 'application/json') {
            if (forceContentType) return res.status(400).send('Invalid content-type. Expecting application/json');
            else return next();
        }
        json(req, res, next);
    };
};
