-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
55 lines (42 loc) · 1.38 KB
/
index.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const typeis = require('type-is');
const { UnsupportedMediaType } = require('http-errors');
const always = () => true;
const bodyPresent = (req) => req.headers['transfer-encoding'] !== undefined ||
!isNaN(req.headers['content-length']);
const bodyNotEmpty = (req) => req.headers['transfer-encoding'] !== undefined ||
Number(req.headers['content-length']) > 0;
const ensureContentType = (contentType, options) => {
if (!Array.isArray(contentType)) {
contentType = [contentType];
}
options = {
when: 'always',
...options,
};
let shouldValidate;
switch (options.when) {
case 'always':
shouldValidate = always;
break;
case 'body-present':
shouldValidate = bodyPresent;
break;
case 'body-not-empty':
shouldValidate = bodyNotEmpty;
break;
default:
throw new TypeError(`Invalid options.when: "${options.when}"`);
}
return (req, res, next) => {
if (!shouldValidate(req)) {
return next();
}
const valid = typeis.is(req.headers['content-type'], contentType);
if (!valid) {
return next(new UnsupportedMediaType(`Invalid content-type, must be one of ${contentType.join(', ')}`));
}
next();
};
};
module.exports = ensureContentType;