send_sample_request.js 8.5 KB

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