All files / take-five/lib parse-body.js

93.75% Statements 15/16
88.89% Branches 8/9
100% Functions 4/4
93.75% Lines 15/16
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 281x   1x 5x 15x 3x 3x 3x       3x     3x 3x 3x   1x   2x   3x   12x      
const Buffer = require('buffer').Buffer
 
module.exports = function (maxSize) {
  return function parseBody (req, res, next) {
    if ((req.method === 'POST' || req.method === 'PUT') && !req.body) {
      const body = []
      req.on('data', (chunk) => {
        Iif (chunk.length > maxSize || Buffer.byteLength(body.join(''), 'utf8') > maxSize) {
          return res.err(413, 'Payload size exceeds maxmium body length')
        }
 
        body.push(chunk.toString('utf8'))
      })
 
      req.on('end', () => {
        try {
          req.body = JSON.parse(body.join(''))
        } catch (err) {
          return res.err(400, 'Payload is not valid JSON')
        }
        next()
      })
      return
    }
    next()
  }
}