okhttp.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. "use strict";
  2. var _ = require('../../lodash'), parseRequest = require('./parseRequest'), sanitize = require('./util').sanitize, addFormParam = require('./util').addFormParam, sanitizeOptions = require('./util').sanitizeOptions;
  3. // Since Java OkHttp requires to add extralines of code to handle methods with body
  4. const METHODS_WITHOUT_BODY = ['GET', 'HEAD', 'COPY', 'UNLOCK', 'UNLINK', 'PURGE', 'LINK', 'VIEW'];
  5. /**
  6. * returns snippet of java okhttp by parsing data from Postman-SDK request object
  7. *
  8. * @param {Object} request - Postman SDK request object
  9. * @param {String} indentString - indentation required for code snippet
  10. * @param {Object} options - Options to tweak code snippet
  11. * @returns {String} - java okhttp code snippet for given request object
  12. */
  13. function makeSnippet(request, indentString, options) {
  14. var isBodyRequired = !(_.includes(METHODS_WITHOUT_BODY, request.method)), snippet = 'OkHttpClient client = new OkHttpClient().newBuilder()\n', requestBody;
  15. if (options.requestTimeout > 0) {
  16. snippet += indentString + `.setConnectTimeout(${options.requestTimeout}, TimeUnit.MILLISECONDS)\n`;
  17. }
  18. if (!options.followRedirect) {
  19. snippet += indentString + '.followRedirects(false)\n';
  20. }
  21. snippet += indentString + '.build();\n';
  22. if (isBodyRequired) {
  23. // The following code handles multiple files in the same formdata param.
  24. // It removes the form data params where the src property is an array of filepath strings
  25. // Splits that array into different form data params with src set as a single filepath string
  26. if (request.body && request.body.mode === 'formdata') {
  27. let formdata = request.body.formdata, formdataArray = [];
  28. formdata.members.forEach((param) => {
  29. let key = param.key, type = param.type, disabled = param.disabled, contentType = param.contentType;
  30. if (type === 'file') {
  31. if (typeof param.src !== 'string') {
  32. if (Array.isArray(param.src) && param.src.length) {
  33. param.src.forEach((filePath) => {
  34. addFormParam(formdataArray, key, param.type, filePath, disabled, contentType);
  35. });
  36. }
  37. else {
  38. addFormParam(formdataArray, key, param.type, '/path/to/file', disabled, contentType);
  39. }
  40. }
  41. else {
  42. addFormParam(formdataArray, key, param.type, param.src, disabled, contentType);
  43. }
  44. }
  45. else {
  46. addFormParam(formdataArray, key, param.type, param.value, disabled, contentType);
  47. }
  48. });
  49. request.body.update({
  50. mode: 'formdata',
  51. formdata: formdataArray
  52. });
  53. }
  54. requestBody = (request.body ? request.body.toJSON() : {});
  55. // snippet for creating mediatype object in java based on content-type of request
  56. snippet += `MediaType mediaType = MediaType.parse("${parseRequest.parseContentType(request)}");\n`;
  57. snippet += parseRequest.parseBody(requestBody, indentString, options.trimRequestBody);
  58. }
  59. snippet += 'Request request = new Request.Builder()\n';
  60. snippet += indentString + `.url("${sanitize(request.url.toString())}")\n`;
  61. snippet += indentString + `.method("${request.method}", ${isBodyRequired ? 'body' : 'null'})\n`;
  62. if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) {
  63. request.addHeader({
  64. key: 'Content-Type',
  65. value: 'application/json'
  66. });
  67. }
  68. // java-okhttp snippet for adding headers to request
  69. snippet += parseRequest.parseHeader(request, indentString);
  70. snippet += indentString + '.build();\n';
  71. snippet += 'Response response = client.newCall(request).execute();';
  72. return snippet;
  73. }
  74. /**
  75. * Used in order to get options for generation of Java okhattp code snippet (i.e. Include Boilerplate code)
  76. *
  77. * @module getOptions
  78. *
  79. * @returns {Array} Options specific to generation of Java okhattp code snippet
  80. */
  81. function getOptions() {
  82. return [
  83. {
  84. name: 'Include boilerplate',
  85. id: 'includeBoilerplate',
  86. type: 'boolean',
  87. default: false,
  88. description: 'Include class definition and import statements in snippet'
  89. },
  90. {
  91. name: 'Set indentation count',
  92. id: 'indentCount',
  93. type: 'positiveInteger',
  94. default: 2,
  95. description: 'Set the number of indentation characters to add per code level'
  96. },
  97. {
  98. name: 'Set indentation type',
  99. id: 'indentType',
  100. type: 'enum',
  101. availableOptions: ['Tab', 'Space'],
  102. default: 'Space',
  103. description: 'Select the character used to indent lines of code'
  104. },
  105. {
  106. name: 'Set request timeout',
  107. id: 'requestTimeout',
  108. type: 'positiveInteger',
  109. default: 0,
  110. description: 'Set number of milliseconds the request should wait for a response ' +
  111. 'before timing out (use 0 for infinity)'
  112. },
  113. {
  114. name: 'Follow redirects',
  115. id: 'followRedirect',
  116. type: 'boolean',
  117. default: true,
  118. description: 'Automatically follow HTTP redirects'
  119. },
  120. {
  121. name: 'Trim request body fields',
  122. id: 'trimRequestBody',
  123. type: 'boolean',
  124. default: false,
  125. description: 'Remove white space and additional lines that may affect the server\'s response'
  126. }
  127. ];
  128. }
  129. /**
  130. * Converts Postman sdk request object to java okhttp code snippet
  131. *
  132. * @module convert
  133. *
  134. * @param {Object} request - postman-SDK request object
  135. * @param {Object} options - Options to tweak code snippet generated in Java-OkHttp
  136. * @param {String} options.indentType - type for indentation eg: Space, Tab
  137. * @param {String} options.indentCount - number of spaces or tabs for indentation.
  138. * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class definition in java
  139. * @param {Boolean} options.followRedirect - whether to enable followredirect
  140. * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not
  141. * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out
  142. * @param {Function} callback - callback function with parameters (error, snippet)
  143. */
  144. function convert(request, options, callback) {
  145. if (_.isFunction(options)) {
  146. callback = options;
  147. options = {};
  148. }
  149. else if (!_.isFunction(callback)) {
  150. throw new Error('Java-OkHttp-Converter: callback is not valid function');
  151. }
  152. options = sanitizeOptions(options, getOptions());
  153. // String representing value of indentation required
  154. var indentString,
  155. // snippets to include java class definition according to options
  156. headerSnippet = '', footerSnippet = '',
  157. // snippet to create request in java okhttp
  158. snippet = '';
  159. indentString = options.indentType === 'Tab' ? '\t' : ' ';
  160. indentString = indentString.repeat(options.indentCount);
  161. if (options.includeBoilerplate) {
  162. headerSnippet = 'import java.io.*;\n' +
  163. 'import okhttp3.*;\n\n' +
  164. 'public class main {\n' +
  165. indentString + 'public static void main(String []args) throws IOException{\n';
  166. footerSnippet = indentString.repeat(2) + 'System.out.println(response.body().string());\n' +
  167. indentString + '}\n}\n';
  168. }
  169. snippet = makeSnippet(request, indentString, options);
  170. // if boilerplate is included then two more indentString needs to be added in snippet
  171. (options.includeBoilerplate) &&
  172. (snippet = indentString.repeat(2) + snippet.split('\n').join('\n' + indentString.repeat(2)) + '\n');
  173. return callback(null, headerSnippet + snippet + footerSnippet);
  174. }
  175. module.exports = {
  176. convert: convert,
  177. getOptions: getOptions
  178. };