'use strict'
var createError = require('http-errors')
var getBody = require('raw-body')
var iconv = require('iconv-lite')
var onFinished = require('on-finished')
var zlib = require('zlib')
module.exports = read
function read (req, res, next, parse, debug, options) {
var length
var opts = options
var stream
req._body = true
var encoding = opts.encoding !== null
? opts.encoding
: null
var verify = opts.verify
try {
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
opts.length = length
opts.encoding = verify
? null
: encoding
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
}))
}
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
setErrorStatus(err, 400)
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
})
}
stream.resume()
onFinished(req, function onfinished () {
next(err)
})
return
}
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
setErrorStatus(err, 403)
next(err)
return
}
}
var str
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
err.body = str === undefined
? body
: str
setErrorStatus(err, 400)
next(err)
return
}
next()
})
}
function contentstream (req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported')
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding
})
}
return stream
}
function setErrorStatus (error, status) {
if (!error.status && !error.statusCode) {
error.status = status
error.statusCode = status
}
}