parseBody.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.parseBody = parseBody;
  6. var _zlib = _interopRequireDefault(require("zlib"));
  7. var _rawBody = _interopRequireDefault(require("raw-body"));
  8. var _httpErrors = _interopRequireDefault(require("http-errors"));
  9. var _querystring = _interopRequireDefault(require("querystring"));
  10. var _contentType = _interopRequireDefault(require("content-type"));
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * Provided a "Request" provided by express or connect (typically a node style
  14. * HTTPClientRequest), Promise the body data contained.
  15. */
  16. async function parseBody(req) {
  17. const {
  18. body
  19. } = req; // If express has already parsed a body as a keyed object, use it.
  20. if (typeof body === 'object' && !(body instanceof Buffer)) {
  21. return body;
  22. } // Skip requests without content types.
  23. if (req.headers['content-type'] === undefined) {
  24. return {};
  25. }
  26. const typeInfo = _contentType.default.parse(req); // If express has already parsed a body as a string, and the content-type
  27. // was application/graphql, parse the string body.
  28. if (typeof body === 'string' && typeInfo.type === 'application/graphql') {
  29. return {
  30. query: body
  31. };
  32. } // Already parsed body we didn't recognise? Parse nothing.
  33. if (body) {
  34. return {};
  35. }
  36. const rawBody = await readBody(req, typeInfo); // Use the correct body parser based on Content-Type header.
  37. switch (typeInfo.type) {
  38. case 'application/graphql':
  39. return {
  40. query: rawBody
  41. };
  42. case 'application/json':
  43. if (jsonObjRegex.test(rawBody)) {
  44. /* eslint-disable no-empty */
  45. try {
  46. return JSON.parse(rawBody);
  47. } catch (error) {} // Do nothing
  48. /* eslint-enable no-empty */
  49. }
  50. throw (0, _httpErrors.default)(400, 'POST body sent invalid JSON.');
  51. case 'application/x-www-form-urlencoded':
  52. return _querystring.default.parse(rawBody);
  53. } // If no Content-Type header matches, parse nothing.
  54. return {};
  55. }
  56. /**
  57. * RegExp to match an Object-opening brace "{" as the first non-space
  58. * in a string. Allowed whitespace is defined in RFC 7159:
  59. *
  60. * ' ' Space
  61. * '\t' Horizontal tab
  62. * '\n' Line feed or New line
  63. * '\r' Carriage return
  64. */
  65. const jsonObjRegex = /^[ \t\n\r]*\{/; // Read and parse a request body.
  66. async function readBody(req, typeInfo) {
  67. const charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase(); // Assert charset encoding per JSON RFC 7159 sec 8.1
  68. if (charset.slice(0, 4) !== 'utf-') {
  69. throw (0, _httpErrors.default)(415, `Unsupported charset "${charset.toUpperCase()}".`);
  70. } // Get content-encoding (e.g. gzip)
  71. const contentEncoding = req.headers['content-encoding'];
  72. const encoding = typeof contentEncoding === 'string' ? contentEncoding.toLowerCase() : 'identity';
  73. const length = encoding === 'identity' ? req.headers['content-length'] : null;
  74. const limit = 100 * 1024; // 100kb
  75. const stream = decompressed(req, encoding); // Read body from stream.
  76. try {
  77. return await (0, _rawBody.default)(stream, {
  78. encoding: charset,
  79. length,
  80. limit
  81. });
  82. } catch (err) {
  83. throw err.type === 'encoding.unsupported' ? (0, _httpErrors.default)(415, `Unsupported charset "${charset.toUpperCase()}".`) : (0, _httpErrors.default)(400, `Invalid body: ${err.message}.`);
  84. }
  85. } // Return a decompressed stream, given an encoding.
  86. function decompressed(req, encoding) {
  87. switch (encoding) {
  88. case 'identity':
  89. return req;
  90. case 'deflate':
  91. return req.pipe(_zlib.default.createInflate());
  92. case 'gzip':
  93. return req.pipe(_zlib.default.createGunzip());
  94. }
  95. throw (0, _httpErrors.default)(415, `Unsupported content-encoding "${encoding}".`);
  96. }