parseRequest.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. "use strict";
  2. const _ = require('../../lodash'), sanitize = require('./util').sanitize, path = require('path');
  3. /**
  4. * parses body of request when type of the request body is formdata or urlencoded and
  5. * returns code snippet for nodejs to add body
  6. *
  7. * @param {Array<Object>} dataArray - array containing body elements of request
  8. * @param {String} indentString - string required for indentation
  9. * @param {Boolean} trimBody - indicates whether to trim body or not
  10. */
  11. function extractFormData(dataArray, indentString, trimBody) {
  12. if (!dataArray) {
  13. return '';
  14. }
  15. var snippetString = _.reduce(dataArray, (accumalator, item) => {
  16. if (item.disabled) {
  17. return accumalator;
  18. }
  19. accumalator.push(indentString + `'${sanitize(item.key, trimBody)}': '${sanitize(item.value, trimBody)}'`);
  20. return accumalator;
  21. }, []);
  22. return snippetString.join(',\n');
  23. }
  24. /**
  25. * Generates multipart form data snippet
  26. *
  27. * @param {*} requestbody
  28. */
  29. function generateMultipartFormData(requestbody) {
  30. const boundary = '------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; ', dataArray = requestbody[requestbody.mode];
  31. var postData = '';
  32. if (dataArray.length) {
  33. postData = '"' + boundary + _.reduce(dataArray, (accumalator, dataArrayElement) => {
  34. if (!dataArrayElement.disabled || dataArrayElement.disabled === false) {
  35. const key = dataArrayElement.key.replace(/"/g, '\'');
  36. if (dataArrayElement.type === 'file') {
  37. var pathArray = dataArrayElement.src.split(path.sep), fileName = pathArray[pathArray.length - 1];
  38. const filename = `filename=\\"${fileName}\\"`, contentType = 'Content-Type: \\"{Insert_File_Content_Type}\\"', fileContent = `fs.readFileSync('${dataArrayElement.src}')`;
  39. // eslint-disable-next-line max-len
  40. accumalator.push(`name=\\"${key}\\"; ${filename}\\r\\n${contentType}\\r\\n\\r\\n" + ${fileContent} + "\\r\\n`);
  41. }
  42. else {
  43. // eslint-disable-next-line no-useless-escape
  44. const value = dataArrayElement.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  45. let field = `name=\\"${key}\\"\\r\\n`;
  46. if (dataArrayElement.contentType) {
  47. field += `Content-Type: ${dataArrayElement.contentType}\\r\\n`;
  48. }
  49. field += `\\r\\n${value}\\r\\n`;
  50. accumalator.push(field);
  51. }
  52. }
  53. return accumalator;
  54. // eslint-disable-next-line no-useless-escape
  55. }, []).join(`${boundary}`) + '------WebKitFormBoundary7MA4YWxkTrZu0gW--\"';
  56. }
  57. return postData;
  58. }
  59. /**
  60. * Parses body object based on mode of body and returns code snippet
  61. *
  62. * @param {Object} requestbody - json object for body of request
  63. * @param {String} indentString - string for indentation
  64. * @param {Boolean} trimBody - indicates whether to trim body fields or not
  65. * @param {String} contentType Content type of the body being sent
  66. */
  67. function parseBody(requestbody, indentString, trimBody, contentType) {
  68. if (requestbody) {
  69. switch (requestbody.mode) {
  70. case 'raw':
  71. // Match any application type whose underlying structure is json
  72. // For example application/vnd.api+json
  73. // All of them have +json as suffix
  74. if (contentType && (contentType === 'application/json' || contentType.match(/\+json$/))) {
  75. try {
  76. let jsonBody = JSON.parse(requestbody[requestbody.mode]);
  77. return `JSON.stringify(${JSON.stringify(jsonBody)})`;
  78. }
  79. catch (error) {
  80. return ` ${JSON.stringify(requestbody[requestbody.mode])}`;
  81. }
  82. }
  83. return ` ${JSON.stringify(requestbody[requestbody.mode])}`;
  84. case 'graphql':
  85. // eslint-disable-next-line no-case-declarations
  86. let query = requestbody[requestbody.mode].query, graphqlVariables;
  87. try {
  88. graphqlVariables = JSON.parse(requestbody[requestbody.mode].variables);
  89. }
  90. catch (e) {
  91. graphqlVariables = {};
  92. }
  93. return 'JSON.stringify({\n' +
  94. `${indentString}query: \`${query.trim()}\`,\n` +
  95. `${indentString}variables: ${JSON.stringify(graphqlVariables)}\n})`;
  96. case 'formdata':
  97. return generateMultipartFormData(requestbody);
  98. case 'urlencoded':
  99. return `qs.stringify({\n${extractFormData(requestbody[requestbody.mode], indentString, trimBody)}` +
  100. '\n})';
  101. case 'file':
  102. return '"<file contents here>"';
  103. default:
  104. return '';
  105. }
  106. }
  107. return '';
  108. }
  109. /**
  110. * parses header of request object and returns code snippet of nodejs native to add header
  111. *
  112. * @param {Object} request - Postman SDK request object
  113. * @param {String} indentString - indentation required in code snippet
  114. * @returns {String} - code snippet of nodejs native to add header
  115. */
  116. function parseHeader(request, indentString) {
  117. var headerObject = request.getHeaders({ enabled: true }), isEmptyHeader = !Object.keys(headerObject).length;
  118. if (isEmptyHeader)
  119. return '';
  120. var headerSnippet = indentString + '\'headers\': {\n';
  121. if (headerObject && Object.keys(headerObject).length) {
  122. headerSnippet += _.reduce(Object.keys(headerObject), function (accumalator, key) {
  123. if (Array.isArray(headerObject[key])) {
  124. var headerValues = [];
  125. _.forEach(headerObject[key], (value) => {
  126. headerValues.push(`'${sanitize(value)}'`);
  127. });
  128. accumalator.push(indentString.repeat(2) + `'${sanitize(key, true)}': [${headerValues.join(', ')}]`);
  129. }
  130. else {
  131. accumalator.push(indentString.repeat(2) + `'${sanitize(key, true)}': '${sanitize(headerObject[key])}'`);
  132. }
  133. return accumalator;
  134. }, []).join(',\n');
  135. }
  136. if (headerObject && !_.isEmpty(headerObject)) {
  137. headerSnippet += '\n';
  138. }
  139. headerSnippet += indentString + '}';
  140. return headerSnippet;
  141. }
  142. module.exports = {
  143. parseBody: parseBody,
  144. parseHeader: parseHeader
  145. };