any.js
1.18 KB
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
/**
* Module dependencies.
*/
var typeis = require('type-is');
var json = require('./json');
var form = require('./form');
var text = require('./text');
var jsonTypes = ['json', 'application/*+json', 'application/csp-report'];
var formTypes = ['urlencoded'];
var textTypes = ['text'];
/**
* Return a Promise which parses form and json requests
* depending on the Content-Type.
*
* Pass a node request or an object with `.req`,
* such as a koa Context.
*
* @param {Request} req
* @param {Options} [opts]
* @return {Function}
* @api public
*/
module.exports = function(req, opts){
req = req.req || req;
opts = opts || {};
// json
var jsonType = opts.jsonTypes || jsonTypes;
if (typeis(req, jsonType)) return json(req, opts);
// form
var formType = opts.formTypes || formTypes;
if (typeis(req, formType)) return form(req, opts);
// text
var textType = opts.textTypes || textTypes;
if (typeis(req, textType)) return text(req, opts);
// invalid
var type = req.headers['content-type'] || '';
var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
var err = new Error(message);
err.status = 415;
return Promise.reject(err);
};