any.js 1.2 KB

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