2017-06-26 19:58:58 +02:00
|
|
|
/*
|
|
|
|
express middleware that sends a 406 Unacceptable
|
|
|
|
response if an incoming request's Content-Type
|
|
|
|
header does not match `type`
|
|
|
|
*/
|
|
|
|
const requestsOfType = type => (req, res, next) => {
|
2019-10-02 22:18:54 +02:00
|
|
|
const hasContentType = req.get('content-type') !== undefined && req.get('content-type') !== null;
|
2019-07-21 16:31:14 +02:00
|
|
|
const isCorrectType = req.is(type) === null || req.is(type) === type;
|
|
|
|
|
|
|
|
if (hasContentType && !isCorrectType) {
|
2017-12-08 20:50:53 +01:00
|
|
|
if (process.env.NODE_ENV === 'development') {
|
2019-07-21 16:31:14 +02:00
|
|
|
console.error(`Requests with a body must be of Content-Type "${type}". Sending HTTP 406`);
|
2017-12-08 20:50:53 +01:00
|
|
|
}
|
2019-07-21 16:31:14 +02:00
|
|
|
return next({ code: 406, message: `Requests with a body must be of Content-Type "${type}"` }); // 406 UNACCEPTABLE
|
2017-06-26 19:58:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
|
|
|
|
export default requestsOfType;
|
|
|
|
export const requestsOfTypeJSON = () => requestsOfType('application/json');
|