send_sample_request.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. define([
  2. 'jquery',
  3. 'lodash',
  4. './utils/send_sample_request_utils'
  5. ], function($, _, utils) {
  6. var initDynamic = function() {
  7. // Button send
  8. $(".sample-request-send").off("click");
  9. $(".sample-request-send").on("click", function(e) {
  10. e.preventDefault();
  11. var $root = $(this).parents("article");
  12. var group = $root.data("group");
  13. var name = $root.data("name");
  14. var version = $root.data("version");
  15. sendSampleRequest(group, name, version, $(this).data("sample-request-type"));
  16. });
  17. // Button clear
  18. $(".sample-request-clear").off("click");
  19. $(".sample-request-clear").on("click", function(e) {
  20. e.preventDefault();
  21. var $root = $(this).parents("article");
  22. var group = $root.data("group");
  23. var name = $root.data("name");
  24. var version = $root.data("version");
  25. clearSampleRequest(group, name, version);
  26. });
  27. }; // initDynamic
  28. function sendSampleRequest(group, name, version, type)
  29. {
  30. var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
  31. // Optional header
  32. var header = {};
  33. $root.find(".sample-request-header:checked").each(function(i, element) {
  34. var group = $(element).data("sample-request-header-group-id");
  35. $root.find("[data-sample-request-header-group=\"" + group + "\"]").each(function(i, element) {
  36. var key = $(element).data("sample-request-header-name");
  37. var value = element.value;
  38. if (typeof element.optional === 'undefined') {
  39. element.optional = true;
  40. }
  41. if ( ! element.optional && element.defaultValue !== '') {
  42. value = element.defaultValue;
  43. }
  44. header[key] = value;
  45. });
  46. });
  47. // create JSON dictionary of parameters
  48. var param = {};
  49. var paramType = {};
  50. var bodyFormData = new FormData();
  51. var bodyJson = '';
  52. $root.find(".sample-request-param:checked").each(function(i, element) {
  53. var group = $(element).data("sample-request-param-group-id");
  54. var contentType = $(element).nextAll('.sample-header-content-type-switch').first().val();
  55. if (contentType == "body-json"){
  56. $root.find("[data-sample-request-body-group=\"" + group + "\"]").not(function(){
  57. return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
  58. }).each(function(i, element) {
  59. if (isJson(element.value)){
  60. header['Content-Type'] = 'application/json';
  61. bodyJson = element.value;
  62. }
  63. });
  64. }else {
  65. $root.find("[data-sample-request-param-group=\"" + group + "\"]").not(function(){
  66. return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
  67. }).each(function(i, element) {
  68. var key = $(element).data("sample-request-param-name");
  69. var value = element.value;
  70. if ( ! element.optional && element.defaultValue !== '') {
  71. value = element.defaultValue;
  72. }
  73. if (contentType == "body-form-data"){
  74. header['Content-Type'] = 'multipart/form-data'
  75. if (element.type == "file") {
  76. value = element.files[0];
  77. }
  78. bodyFormData.append(key,value);
  79. }else {
  80. param[key] = value;
  81. paramType[key] = $(element).next().text();
  82. }
  83. });
  84. }
  85. });
  86. // grab user-inputted URL
  87. var url = $root.find(".sample-request-url").val();
  88. //Convert {param} form to :param
  89. url = utils.convertPathParams(url);
  90. // Insert url parameter
  91. var pattern = pathToRegexp(url, null);
  92. var matches = pattern.exec(url);
  93. for (var i = 1; i < matches.length; i++) {
  94. var key = matches[i].substr(1);
  95. if (param[key] !== undefined) {
  96. url = url.replace(matches[i], encodeURIComponent(param[key]));
  97. // remove URL parameters from list
  98. delete param[key];
  99. }
  100. } // for
  101. //handle nested objects and parsing fields
  102. param = utils.handleNestedAndParsingFields(param, paramType);
  103. //add url search parameter
  104. if (header['Content-Type'] == 'application/json' ){
  105. url = url + encodeSearchParams(param);
  106. param = bodyJson;
  107. }else if (header['Content-Type'] == 'multipart/form-data'){
  108. url = url + encodeSearchParams(param);
  109. param = bodyFormData;
  110. }
  111. $root.find(".sample-request-response").fadeTo(250, 1);
  112. $root.find(".sample-request-response-json").html("Loading...");
  113. refreshScrollSpy();
  114. // send AJAX request, catch success or error callback
  115. var ajaxRequest = {
  116. url : url,
  117. headers : header,
  118. data : param,
  119. type : type.toUpperCase(),
  120. success : displaySuccess,
  121. error : displayError
  122. };
  123. if(header['Content-Type'] == 'multipart/form-data'){
  124. delete ajaxRequest.headers['Content-Type'];
  125. ajaxRequest.contentType=false;
  126. ajaxRequest.processData=false;
  127. }
  128. $.ajax(ajaxRequest);
  129. function displaySuccess(data, status, jqXHR) {
  130. var jsonResponse;
  131. try {
  132. jsonResponse = JSON.parse(jqXHR.responseText);
  133. jsonResponse = JSON.stringify(jsonResponse, null, 4);
  134. } catch (e) {
  135. jsonResponse = jqXHR.responseText;
  136. }
  137. $root.find(".sample-request-response-json").text(jsonResponse);
  138. refreshScrollSpy();
  139. };
  140. function displayError(jqXHR, textStatus, error) {
  141. var message = "Error " + jqXHR.status + ": " + error;
  142. var jsonResponse;
  143. try {
  144. jsonResponse = JSON.parse(jqXHR.responseText);
  145. jsonResponse = JSON.stringify(jsonResponse, null, 4);
  146. } catch (e) {
  147. jsonResponse = jqXHR.responseText;
  148. }
  149. if (jsonResponse)
  150. message += "\n" + jsonResponse;
  151. // flicker on previous error to make clear that there is a new response
  152. if($root.find(".sample-request-response").is(":visible"))
  153. $root.find(".sample-request-response").fadeTo(1, 0.1);
  154. $root.find(".sample-request-response").fadeTo(250, 1);
  155. $root.find(".sample-request-response-json").text(message);
  156. refreshScrollSpy();
  157. };
  158. }
  159. function clearSampleRequest(group, name, version)
  160. {
  161. var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
  162. // hide sample response
  163. $root.find(".sample-request-response-json").html("");
  164. $root.find(".sample-request-response").hide();
  165. // reset value of parameters
  166. $root.find(".sample-request-param").each(function(i, element) {
  167. element.value = "";
  168. });
  169. // restore default URL
  170. var $urlElement = $root.find(".sample-request-url");
  171. $urlElement.val($urlElement.prop("defaultValue"));
  172. refreshScrollSpy();
  173. }
  174. function refreshScrollSpy()
  175. {
  176. $('[data-spy="scroll"]').each(function () {
  177. $(this).scrollspy("refresh");
  178. });
  179. }
  180. function escapeHtml(str) {
  181. var div = document.createElement("div");
  182. div.appendChild(document.createTextNode(str));
  183. return div.innerHTML;
  184. }
  185. /**
  186. * is Json
  187. */
  188. function isJson(str) {
  189. if (typeof str == 'string') {
  190. try {
  191. var obj=JSON.parse(str);
  192. if(typeof obj == 'object' && obj ){
  193. return true;
  194. }else{
  195. return false;
  196. }
  197. } catch(e) {
  198. return false;
  199. }
  200. }
  201. }
  202. /**
  203. * encode Search Params
  204. */
  205. function encodeSearchParams(obj) {
  206. const params = [];
  207. Object.keys(obj).forEach((key) => {
  208. let value = obj[key];
  209. params.push([key, encodeURIComponent(value)].join('='));
  210. })
  211. return params.length === 0 ? '' : '?' + params.join('&');
  212. }
  213. /**
  214. * Exports.
  215. */
  216. return {
  217. initDynamic: initDynamic
  218. };
  219. });