UNPKG

1.2 kBJavaScriptView Raw
1
2/**
3 * Module dependencies.
4 */
5
6var typeis = require('type-is');
7var json = require('./json');
8var form = require('./form');
9var text = require('./text');
10
11var jsonTypes = ['json', 'application/*+json', 'application/csp-report'];
12var formTypes = ['urlencoded'];
13var textTypes = ['text'];
14
15/**
16 * Return a Promise which parses form and json requests
17 * depending on the Content-Type.
18 *
19 * Pass a node request or an object with `.req`,
20 * such as a koa Context.
21 *
22 * @param {Request} req
23 * @param {Options} [opts]
24 * @return {Function}
25 * @api public
26 */
27
28module.exports = function(req, opts){
29 req = req.req || req;
30 opts = opts || {};
31
32 // json
33 var jsonType = opts.jsonTypes || jsonTypes;
34 if (typeis(req, jsonType)) return json(req, opts);
35
36 // form
37 var formType = opts.formTypes || formTypes;
38 if (typeis(req, formType)) return form(req, opts);
39
40 // text
41 var textType = opts.textTypes || textTypes;
42 if (typeis(req, textType)) return text(req, opts);
43
44 // invalid
45 var type = req.headers['content-type'] || '';
46 var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
47 var err = new Error(message);
48 err.status = 415;
49 return Promise.reject(err);
50};