3 * Copyright(c) 2014 Douglas Christopher Wilson
11 var getBody = require('raw-body')
12 var iconv = require('iconv-lite')
13 var onFinished = require('on-finished')
14 var typer = require('media-typer')
15 var zlib = require('zlib')
24 * Read a request into a buffer and parse.
28 * @param {function} next
29 * @param {function} parse
30 * @param {object} options
34 function read(req, res, next, parse, options) {
42 stream = contentstream(req, options.inflate)
43 length = stream.length
49 options = options || {}
50 options.length = length
52 var encoding = options.encoding !== null
53 ? options.encoding || 'utf-8'
55 var verify = options.verify
57 options.encoding = verify
62 getBody(stream, options, function (err, body) {
69 if (err.type === 'encoding.unsupported') {
70 err = new Error('unsupported charset "' + encoding.toUpperCase() + '"')
71 err.charset = encoding.toLowerCase()
75 // read off entire request
77 onFinished(req, function onfinished() {
86 verify(req, res, body, encoding)
88 if (!err.status) err.status = 403
95 body = typeof body !== 'string' && encoding !== null
96 ? iconv.decode(body, encoding)
98 req.body = parse(body)
112 * Get the content stream of the request.
114 * @param {object} req
115 * @param {boolean} [inflate=true]
120 function contentstream(req, inflate) {
121 var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
123 var length = req.headers['content-length']
126 if (inflate === false && encoding !== 'identity') {
127 err = new Error('content encoding unsupported')
134 stream = zlib.createInflate()
138 stream = zlib.createGunzip()
143 stream.length = length
146 err = new Error('unsupported content encoding "' + encoding + '"')
147 err.encoding = encoding