Initial commit
[yaffs-website] / node_modules / body-parser / lib / types / raw.js
1 /*!
2  * body-parser
3  * Copyright(c) 2014-2015 Douglas Christopher Wilson
4  * MIT Licensed
5  */
6
7 'use strict'
8
9 /**
10  * Module dependencies.
11  */
12
13 var bytes = require('bytes')
14 var debug = require('debug')('body-parser:raw')
15 var read = require('../read')
16 var typeis = require('type-is')
17
18 /**
19  * Module exports.
20  */
21
22 module.exports = raw
23
24 /**
25  * Create a middleware to parse raw bodies.
26  *
27  * @param {object} [options]
28  * @return {function}
29  * @api public
30  */
31
32 function raw(options) {
33   var opts = options || {};
34
35   var inflate = opts.inflate !== false
36   var limit = typeof opts.limit !== 'number'
37     ? bytes.parse(opts.limit || '100kb')
38     : opts.limit
39   var type = opts.type || 'application/octet-stream'
40   var verify = opts.verify || false
41
42   if (verify !== false && typeof verify !== 'function') {
43     throw new TypeError('option verify must be function')
44   }
45
46   // create the appropriate type checking function
47   var shouldParse = typeof type !== 'function'
48     ? typeChecker(type)
49     : type
50
51   function parse(buf) {
52     return buf
53   }
54
55   return function rawParser(req, res, next) {
56     if (req._body) {
57       return debug('body already parsed'), next()
58     }
59
60     req.body = req.body || {}
61
62     // skip requests without bodies
63     if (!typeis.hasBody(req)) {
64       return debug('skip empty body'), next()
65     }
66
67     debug('content-type %j', req.headers['content-type'])
68
69     // determine if request should be parsed
70     if (!shouldParse(req)) {
71       return debug('skip parsing'), next()
72     }
73
74     // read
75     read(req, res, next, parse, debug, {
76       encoding: null,
77       inflate: inflate,
78       limit: limit,
79       verify: verify
80     })
81   }
82 }
83
84 /**
85  * Get the simple type checker.
86  *
87  * @param {string} type
88  * @return {function}
89  */
90
91 function typeChecker(type) {
92   return function checkType(req) {
93     return Boolean(typeis(req, type))
94   }
95 }