tryitout.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. function tryItOut(endpointId) {
  2. document.querySelector(`#btn-tryout-${endpointId}`).hidden = true;
  3. document.querySelector(`#btn-executetryout-${endpointId}`).hidden = false;
  4. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = false;
  5. // Show all input fields
  6. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  7. .forEach(el => el.hidden = false);
  8. if (document.querySelector(`#form-${endpointId}`).dataset.authed === "1") {
  9. const authElement = document.querySelector(`#auth-${endpointId}`);
  10. authElement && (authElement.hidden = false);
  11. }
  12. // Expand all nested fields
  13. document.querySelectorAll(`#form-${endpointId} details`)
  14. .forEach(el => el.open = true);
  15. }
  16. function cancelTryOut(endpointId) {
  17. document.querySelector(`#btn-tryout-${endpointId}`).hidden = false;
  18. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  19. executeBtn.hidden = true;
  20. executeBtn.textContent = "Send Request 💥";
  21. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = true;
  22. // hide inputs
  23. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  24. .forEach(el => el.hidden = true);
  25. document.querySelectorAll(`#form-${endpointId} details`)
  26. .forEach(el => el.open = false);
  27. const authElement = document.querySelector(`#auth-${endpointId}`);
  28. authElement && (authElement.hidden = true);
  29. document.querySelector('#execution-results-' + endpointId).hidden = true;
  30. document.querySelector('#execution-error-' + endpointId).hidden = true;
  31. // Revert to sample code blocks
  32. const query = new URLSearchParams(window.location.search);
  33. const languages = JSON.parse(document.querySelector('body').dataset.languages);
  34. const currentLanguage = languages.find(l => query.has(l)) || languages[0];
  35. let codeblock = getPreviousSiblingUntil(document.querySelector('#form-' + endpointId), 'blockquote,pre', 'h2');
  36. while (codeblock != null) {
  37. if (codeblock.nodeName === 'PRE') {
  38. if (codeblock.querySelector('code.language-' + currentLanguage)) {
  39. codeblock.style.display = 'block';
  40. }
  41. } else {
  42. codeblock.style.display = 'block';
  43. }
  44. codeblock = getPreviousSiblingUntil(codeblock, 'blockquote,pre', 'h2');
  45. }
  46. }
  47. function makeAPICall(method, path, body, query, headers) {
  48. console.log({path, body, query, headers});
  49. if (!(body instanceof FormData)) {
  50. body = JSON.stringify(body)
  51. }
  52. const url = new URL(window.baseUrl + '/' + path.replace(/^\//, ''));
  53. // We need this function because if you try to set an array or object directly to a URLSearchParams object,
  54. // you'll get [object Object] or the array.toString()
  55. function addItemToSearchParamsObject(key, value, searchParams) {
  56. if (Array.isArray(value)) {
  57. value.forEach((v, i) => {
  58. // Append {filters: [first, second]} as filters[0]=first&filters[1]second
  59. addItemToSearchParamsObject(key + '[' + i + ']', v, searchParams);
  60. })
  61. } else if (typeof value === 'object' && value !== null) {
  62. Object.keys(value).forEach((i) => {
  63. // Append {filters: {name: first}} as filters[name]=first
  64. addItemToSearchParamsObject(key + '[' + i + ']', value[i], searchParams);
  65. });
  66. } else {
  67. searchParams.append(key, value);
  68. }
  69. }
  70. Object.keys(query)
  71. .forEach(key => addItemToSearchParamsObject(key, query[key], url.searchParams));
  72. return fetch(url, {
  73. method,
  74. headers,
  75. body: method === 'GET' ? undefined : body,
  76. })
  77. .then(response => Promise.all([response.status, response.text(), response.headers]));
  78. }
  79. function hideCodeSamples(form) {
  80. let codeblock = getPreviousSiblingUntil(form, 'blockquote,pre', 'h2');
  81. while (codeblock != null) {
  82. codeblock.style.display = 'none';
  83. codeblock = getPreviousSiblingUntil(codeblock, 'blockquote,pre', 'h2');
  84. }
  85. }
  86. function handleResponse(form, endpointId, response, status, headers) {
  87. hideCodeSamples(form);
  88. // Hide error views
  89. document.querySelector('#execution-error-' + endpointId).hidden = true;
  90. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  91. // prettify it if it's JSON
  92. let isJson = false;
  93. try {
  94. const jsonParsed = JSON.parse(response);
  95. if (jsonParsed !== null) {
  96. isJson = true;
  97. response = JSON.stringify(jsonParsed, null, 4);
  98. }
  99. } catch (e) {
  100. }
  101. responseContentEl.textContent = response === '' ? '<Empty response>' : response;
  102. isJson && window.hljs.highlightBlock(responseContentEl);
  103. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  104. statusEl.textContent = ` (${status})`;
  105. document.querySelector('#execution-results-' + endpointId).hidden = false;
  106. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  107. }
  108. function handleError(form, endpointId, err) {
  109. hideCodeSamples(form);
  110. // Hide response views
  111. document.querySelector('#execution-results-' + endpointId).hidden = true;
  112. // Show error views
  113. let errorMessage = err.message || err;
  114. errorMessage += "\n\nTip: Check that you're properly connected to the network.";
  115. errorMessage += "\nIf you're a maintainer of ths API, verify that your API is running and you've enabled CORS.";
  116. errorMessage += "\nYou can check the Dev Tools console for debugging information.";
  117. document.querySelector('#execution-error-message-' + endpointId).textContent = errorMessage;
  118. const errorEl = document.querySelector('#execution-error-' + endpointId);
  119. errorEl.hidden = false;
  120. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  121. }
  122. async function executeTryOut(endpointId, form) {
  123. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  124. executeBtn.textContent = "⏱ Sending...";
  125. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  126. let body;
  127. let setter;
  128. if (form.dataset.hasfiles === "0") {
  129. body = {};
  130. setter = (name, value) => _.set(body, name, value);
  131. } else {
  132. body = new FormData();
  133. setter = (name, value) => body.append(name, value);
  134. }
  135. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  136. bodyParameters.forEach(el => {
  137. let value = el.value;
  138. if (el.type === 'file' && el.files[0]) {
  139. setter(el.name, el.files[0]);
  140. return;
  141. }
  142. if (el.type !== 'radio') {
  143. if (value === "" && el.required === false) {
  144. // Don't include empty optional values in the request
  145. return;
  146. }
  147. setter(el.name, value);
  148. return;
  149. }
  150. if (el.checked) {
  151. value = (value === 'false') ? false : true;
  152. setter(el.name, value);
  153. }
  154. });
  155. const query = {};
  156. const queryParameters = form.querySelectorAll('input[data-component=query]');
  157. queryParameters.forEach(el => _.set(query, el.name, el.value));
  158. let path = form.dataset.path;
  159. const urlParameters = form.querySelectorAll('input[data-component=url]');
  160. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  161. const headers = JSON.parse(form.dataset.headers);
  162. // Check for auth param that might go in header
  163. if (form.dataset.authed === "1") {
  164. const authHeaderEl = form.querySelector('input[data-component=header]');
  165. if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
  166. }
  167. // When using FormData, the browser sets the correct content-type + boundary
  168. if (headers['Content-Type'] === "multipart/form-data") {
  169. delete headers['Content-Type'];
  170. }
  171. makeAPICall(form.dataset.method, path, body, query, headers)
  172. .then(([responseStatus, responseContent, responseHeaders]) => {
  173. handleResponse(form, endpointId, responseContent, responseStatus, responseHeaders)
  174. })
  175. .catch(err => {
  176. console.log("Error while making request: ", err);
  177. handleError(form, endpointId, err);
  178. })
  179. .finally(() => {
  180. executeBtn.textContent = "Send Request 💥";
  181. });
  182. }
  183. function getPreviousSiblingUntil(elem, siblingSelector, stopSelector) {
  184. let sibling = elem.previousElementSibling;
  185. while (sibling) {
  186. if (sibling.matches(siblingSelector)) return sibling;
  187. if (sibling.matches(stopSelector)) return null;
  188. sibling = sibling.previousElementSibling;
  189. }
  190. }