any.js 1.2 KB

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