text.js 940 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. const raw = require('raw-body');
  6. const inflate = require('inflation');
  7. const utils = require('./utils');
  8. /**
  9. * Return a Promise which parses text/plain requests.
  10. *
  11. * Pass a node request or an object with `.req`,
  12. * such as a koa Context.
  13. *
  14. * @param {Request} req
  15. * @param {Options} [opts]
  16. * @return {Function}
  17. * @api public
  18. */
  19. module.exports = async function(req, opts) {
  20. req = req.req || req;
  21. opts = utils.clone(opts);
  22. // defaults
  23. const len = req.headers['content-length'];
  24. const encoding = req.headers['content-encoding'] || 'identity';
  25. if (len && encoding === 'identity') opts.length = ~~len;
  26. opts.encoding = opts.encoding === undefined ? 'utf8' : opts.encoding;
  27. opts.limit = opts.limit || '1mb';
  28. const str = await raw(inflate(req), opts);
  29. // ensure return the same format with json / form
  30. return opts.returnRawBody ? { parsed: str, raw: str } : str;
  31. };