tryitout.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. window.abortControllers = {};
  2. function cacheAuthValue() {
  3. // Whenever the auth header is set for one endpoint, cache it for the others
  4. window.lastAuthValue = '';
  5. let authInputs = document.querySelectorAll(`.auth-value`)
  6. authInputs.forEach(el => {
  7. el.addEventListener('input', (event) => {
  8. window.lastAuthValue = event.target.value;
  9. authInputs.forEach(otherInput => {
  10. if (otherInput === el) return;
  11. // Don't block the main thread
  12. setTimeout(() => {
  13. otherInput.value = window.lastAuthValue;
  14. }, 0);
  15. });
  16. });
  17. });
  18. }
  19. window.addEventListener('DOMContentLoaded', cacheAuthValue);
  20. function getCookie(name) {
  21. if (!document.cookie) {
  22. return null;
  23. }
  24. const cookies = document.cookie.split(';')
  25. .map(c => c.trim())
  26. .filter(c => c.startsWith(name + '='));
  27. if (cookies.length === 0) {
  28. return null;
  29. }
  30. return decodeURIComponent(cookies[0].split('=')[1]);
  31. }
  32. function tryItOut(endpointId) {
  33. document.querySelector(`#btn-tryout-${endpointId}`).hidden = true;
  34. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = false;
  35. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`).hidden = false;
  36. executeBtn.disabled = false;
  37. // Show all input fields
  38. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  39. .forEach(el => el.style.display = 'block');
  40. if (document.querySelector(`#form-${endpointId}`).dataset.authed === "1") {
  41. const authElement = document.querySelector(`#auth-${endpointId}`);
  42. authElement && (authElement.hidden = false);
  43. }
  44. // Expand all nested fields
  45. document.querySelectorAll(`#form-${endpointId} details`)
  46. .forEach(el => el.open = true);
  47. }
  48. function cancelTryOut(endpointId) {
  49. if (window.abortControllers[endpointId]) {
  50. window.abortControllers[endpointId].abort();
  51. delete window.abortControllers[endpointId];
  52. }
  53. document.querySelector(`#btn-tryout-${endpointId}`).hidden = false;
  54. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  55. executeBtn.hidden = true;
  56. executeBtn.textContent = executeBtn.dataset.initialText;
  57. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = true;
  58. // Hide inputs
  59. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  60. .forEach(el => el.style.display = 'none');
  61. document.querySelectorAll(`#form-${endpointId} details`)
  62. .forEach(el => el.open = false);
  63. const authElement = document.querySelector(`#auth-${endpointId}`);
  64. authElement && (authElement.hidden = true);
  65. document.querySelector('#execution-results-' + endpointId).hidden = true;
  66. document.querySelector('#execution-error-' + endpointId).hidden = true;
  67. // Revert to sample code blocks
  68. document.querySelector('#example-requests-' + endpointId).hidden = false;
  69. document.querySelector('#example-responses-' + endpointId).hidden = false;
  70. }
  71. function makeAPICall(method, path, body = {}, query = {}, headers = {}, endpointId = null) {
  72. console.log({endpointId, path, body, query, headers});
  73. if (!(body instanceof FormData) && typeof body !== "string") {
  74. body = JSON.stringify(body)
  75. }
  76. const url = new URL(window.tryItOutBaseUrl + '/' + path.replace(/^\//, ''));
  77. // We need this function because if you try to set an array or object directly to a URLSearchParams object,
  78. // you'll get [object Object] or the array.toString()
  79. function addItemToSearchParamsObject(key, value, searchParams) {
  80. if (Array.isArray(value)) {
  81. value.forEach((v, i) => {
  82. // Append {filters: [first, second]} as filters[0]=first&filters[1]second
  83. addItemToSearchParamsObject(key + '[' + i + ']', v, searchParams);
  84. })
  85. } else if (typeof value === 'object' && value !== null) {
  86. Object.keys(value).forEach((i) => {
  87. // Append {filters: {name: first}} as filters[name]=first
  88. addItemToSearchParamsObject(key + '[' + i + ']', value[i], searchParams);
  89. });
  90. } else {
  91. searchParams.append(key, value);
  92. }
  93. }
  94. Object.keys(query)
  95. .forEach(key => addItemToSearchParamsObject(key, query[key], url.searchParams));
  96. window.abortControllers[endpointId] = new AbortController();
  97. return fetch(url, {
  98. method,
  99. headers,
  100. body: method === 'GET' ? undefined : body,
  101. signal: window.abortControllers[endpointId].signal,
  102. referrer: window.tryItOutBaseUrl,
  103. mode: 'cors',
  104. credentials: 'same-origin',
  105. })
  106. .then(response => Promise.all([response.status, response.statusText, response.text(), response.headers]));
  107. }
  108. function hideCodeSamples(endpointId) {
  109. document.querySelector('#example-requests-' + endpointId).hidden = true;
  110. document.querySelector('#example-responses-' + endpointId).hidden = true;
  111. }
  112. function handleResponse(endpointId, response, status, headers) {
  113. hideCodeSamples(endpointId);
  114. // Hide error views
  115. document.querySelector('#execution-error-' + endpointId).hidden = true;
  116. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  117. // Prettify it if it's JSON
  118. let isJson = false;
  119. try {
  120. const jsonParsed = JSON.parse(response);
  121. if (jsonParsed !== null) {
  122. isJson = true;
  123. response = JSON.stringify(jsonParsed, null, 4);
  124. }
  125. } catch (e) {
  126. }
  127. responseContentEl.textContent = response === '' ? responseContentEl.dataset.emptyResponseText : response;
  128. isJson && window.hljs.highlightElement(responseContentEl);
  129. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  130. statusEl.textContent = ` (${status})`;
  131. document.querySelector('#execution-results-' + endpointId).hidden = false;
  132. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  133. }
  134. function handleError(endpointId, err) {
  135. hideCodeSamples(endpointId);
  136. // Hide response views
  137. document.querySelector('#execution-results-' + endpointId).hidden = true;
  138. // Show error views
  139. let errorMessage = err.message || err;
  140. const $errorMessageEl = document.querySelector('#execution-error-message-' + endpointId);
  141. $errorMessageEl.textContent = errorMessage + $errorMessageEl.textContent;
  142. const errorEl = document.querySelector('#execution-error-' + endpointId);
  143. errorEl.hidden = false;
  144. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  145. }
  146. async function executeTryOut(endpointId, form) {
  147. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  148. executeBtn.textContent = executeBtn.dataset.loadingText;
  149. executeBtn.disabled = true;
  150. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  151. let body;
  152. let setter;
  153. if (form.dataset.hasfiles === "1") {
  154. body = new FormData();
  155. setter = (name, value) => body.append(name, value);
  156. } else if (form.dataset.isarraybody === "1") {
  157. body = [];
  158. setter = (name, value) => _.set(body, name, value);
  159. } else {
  160. body = {};
  161. setter = (name, value) => _.set(body, name, value);
  162. }
  163. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  164. bodyParameters.forEach(el => {
  165. let value = el.value;
  166. if (el.type === 'file' && el.files[0]) {
  167. setter(el.name, el.files[0]);
  168. return;
  169. }
  170. if (el.type !== 'radio') {
  171. if (value === "" && el.required === false) {
  172. // Don't include empty optional values in the request
  173. return;
  174. }
  175. setter(el.name, value);
  176. return;
  177. }
  178. if (el.checked) {
  179. value = (value === 'false') ? false : true;
  180. setter(el.name, value);
  181. }
  182. });
  183. const query = {};
  184. const queryParameters = form.querySelectorAll('input[data-component=query]');
  185. queryParameters.forEach(el => {
  186. if (el.type !== 'radio' || (el.type === 'radio' && el.checked)) {
  187. if (el.value === '') {
  188. // Don't include empty values in the request
  189. return;
  190. }
  191. _.set(query, el.name, el.value);
  192. }
  193. });
  194. let path = form.dataset.path;
  195. const urlParameters = form.querySelectorAll('input[data-component=url]');
  196. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  197. const headers = Object.fromEntries(Array.from(form.querySelectorAll('input[data-component=header]'))
  198. .map(el => [el.name, el.value]));
  199. // When using FormData, the browser sets the correct content-type + boundary
  200. let method = form.dataset.method;
  201. if (body instanceof FormData) {
  202. delete headers['Content-Type'];
  203. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  204. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  205. method = 'POST';
  206. setter('_method', form.dataset.method);
  207. }
  208. }
  209. let preflightPromise = Promise.resolve();
  210. if (window.useCsrf && window.csrfUrl) {
  211. preflightPromise = makeAPICall('GET', window.csrfUrl).then(() => {
  212. headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
  213. });
  214. }
  215. return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
  216. .then(([responseStatus, statusText, responseContent, responseHeaders]) => {
  217. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  218. })
  219. .catch(err => {
  220. if (err.name === "AbortError") {
  221. console.log("Request cancelled");
  222. return;
  223. }
  224. console.log("Error while making request: ", err);
  225. handleError(endpointId, err);
  226. })
  227. .finally(() => {
  228. executeBtn.disabled = false;
  229. executeBtn.textContent = executeBtn.dataset.initialText;
  230. });
  231. }