tryitout.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 = "Execute";
  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. Object.keys(query)
  54. .forEach(key => url.searchParams.append(key, query[key]));
  55. return fetch(url, {
  56. method,
  57. headers,
  58. body: method === 'GET' ? undefined : body,
  59. })
  60. .then(response => Promise.all([response.status, response.text(), response.headers]));
  61. }
  62. function hideCodeSamples(form) {
  63. let codeblock = getPreviousSiblingUntil(form, 'blockquote,pre', 'h2');
  64. while (codeblock != null) {
  65. codeblock.style.display = 'none';
  66. codeblock = getPreviousSiblingUntil(codeblock, 'blockquote,pre', 'h2');
  67. }
  68. }
  69. function handleResponse(form, endpointId, response, status, headers) {
  70. hideCodeSamples(form);
  71. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  72. // prettify it if it's JSON
  73. let isJson = false;
  74. try {
  75. const jsonParsed = JSON.parse(response);
  76. if (jsonParsed !== null) {
  77. isJson = true;
  78. response = JSON.stringify(jsonParsed, null, 4);
  79. }
  80. } catch (e) {
  81. }
  82. responseContentEl.textContent = response === '' ? '<Empty response>' : response;
  83. isJson && window.hljs.highlightBlock(responseContentEl);
  84. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  85. statusEl.textContent = ` (${status})`;
  86. document.querySelector('#execution-results-' + endpointId).hidden = false;
  87. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  88. }
  89. function handleError(form, endpointId, err) {
  90. document.querySelector('#execution-error-message-' + endpointId).textContent = err.message || err;
  91. hideCodeSamples(form);
  92. const errorEl = document.querySelector('#execution-error-' + endpointId);
  93. errorEl.hidden = false;
  94. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  95. }
  96. async function executeTryOut(endpointId, form) {
  97. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  98. executeBtn.textContent = "⏱ Executing...";
  99. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  100. let body;
  101. let setter;
  102. if (form.dataset.hasfiles === "0") {
  103. body = {};
  104. setter = (name, value) => _.set(body, name, value);
  105. } else {
  106. body = new FormData();
  107. setter = (name, value) => body.append(name, value);
  108. }
  109. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  110. bodyParameters.forEach(el => {
  111. let value = el.value;
  112. if (el.type === 'file' && el.files[0]) {
  113. setter(el.name, el.files[0]);
  114. return;
  115. }
  116. if (el.type !== 'radio') {
  117. if (value === "" && el.required === false) {
  118. // Don't include empty optional values in the request
  119. return;
  120. }
  121. setter(el.name, value);
  122. return;
  123. }
  124. if (el.checked) {
  125. value = (value === 'false') ? false : true;
  126. setter(el.name, value);
  127. }
  128. });
  129. const query = {};
  130. const queryParameters = form.querySelectorAll('input[data-component=query]');
  131. queryParameters.forEach(el => _.set(query, el.name, el.value));
  132. let path = form.dataset.path;
  133. const urlParameters = form.querySelectorAll('input[data-component=url]');
  134. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  135. const headers = JSON.parse(form.dataset.headers);
  136. // Check for auth param that might go in header
  137. if (form.dataset.authed === "1") {
  138. const authHeaderEl = form.querySelector('input[data-component=header]');
  139. if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
  140. }
  141. makeAPICall(form.dataset.method, path, body, query, headers)
  142. .then(([responseStatus, responseContent, responseHeaders]) => {
  143. handleResponse(form, endpointId, responseContent, responseStatus, responseHeaders)
  144. })
  145. .catch(err => {
  146. console.log("Error while making request: ", err);
  147. handleError(form, endpointId, err);
  148. })
  149. .finally(() => {
  150. executeBtn.textContent = "Execute";
  151. });
  152. }
  153. function getPreviousSiblingUntil(elem, siblingSelector, stopSelector) {
  154. let sibling = elem.previousElementSibling;
  155. while (sibling) {
  156. if (sibling.matches(siblingSelector)) return sibling;
  157. if (sibling.matches(stopSelector)) return null;
  158. sibling = sibling.previousElementSibling;
  159. }
  160. }