This repository was archived by the owner on Mar 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrequest-body.js
83 lines (65 loc) · 1.91 KB
/
request-body.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const rawBody = require('raw-body')
const typer = require('media-typer')
const helpers = require('../helpers')
const encoding = 'utf8'
module.exports = function requestBody (middleware, filter) {
return function (req, res, next) {
// Ignore HTTP verbs that does not support bodies
if (req.method === 'GET' || req.method === 'HEAD') {
return next()
}
// Apply request filter, if defined
if (filter && !helpers.filterRequest(filter, req)) {
return next()
}
// If body is already present, just continue with it
if (req.body) {
return middleware(req, res, setBody)
}
const type = req.headers['content-type']
const length = req.headers['content-length']
const bodyParams = {
length: length,
encoding: getEncoding(type)
}
// Read the whole payload
rawBody(req, bodyParams, getBody)
function getBody (err, body) {
if (err) return next(err)
req.body = req._originalBody = body
const bodyLength = +(length || Buffer.byteLength(body))
if (bodyLength) req._originalBodyLength = bodyLength
// Parse body for convenience
if (isJSON(type)) parseJSON(req)
middleware(req, res, setBody)
}
function setBody (err, body, enc) {
if (err) return next(err)
if (body) {
// Expose the new body in the request
req.headers['content-length'] = Buffer.byteLength(body)
req.body = req._newBody = body
req._newBodyEncoding = enc || encoding
}
next()
}
}
}
function parseJSON (req) {
if (req.json) return
const body = req.body || ''
try {
req.json = JSON.parse(body.toString())
} catch (e) {
req.parseError = e
}
}
function isJSON (type) {
return /json/i.test(type)
}
function getEncoding (type) {
if (!type) return encoding
const parsed = typer.parse(type)
if (parsed) return parsed.parameters.charset || encoding
return encoding
}