-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathcontent_type_checker.ts
35 lines (33 loc) · 1.17 KB
/
content_type_checker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type { RequestHandler } from 'express';
import { is } from 'type-is';
import ContentTypeError from '../error/content-type-error';
const DEFAULT_ACCEPTED_CONTENT_TYPE = 'application/json';
/**
* Builds an express middleware checking the content-type header
* returning 415 if the header is not either `application/json` or in the array
* passed into the function of valid content-types
* @param {String} acceptedContentTypes
* @returns {function(Request, Response, NextFunction): void}
*/
export default function requireContentType(
...acceptedContentTypes: string[]
): RequestHandler {
if (acceptedContentTypes.length === 0) {
acceptedContentTypes.push(DEFAULT_ACCEPTED_CONTENT_TYPE);
}
return (req, res, next) => {
const contentType = req.header('Content-Type');
if (
contentType !== undefined &&
is(contentType, acceptedContentTypes)
) {
next();
} else {
const error = new ContentTypeError(
acceptedContentTypes as [string, ...string[]],
contentType,
);
res.status(error.statusCode).json(error).end();
}
};
}