tryitout.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 === 'number' && typeof value === 'string') {
  167. value = parseFloat(value);
  168. }
  169. if (el.type === 'file' && el.files[0]) {
  170. setter(el.name, el.files[0]);
  171. return;
  172. }
  173. if (el.type !== 'radio') {
  174. if (value === "" && el.required === false) {
  175. // Don't include empty optional values in the request
  176. return;
  177. }
  178. setter(el.name, value);
  179. return;
  180. }
  181. if (el.checked) {
  182. value = (value === 'false') ? false : true;
  183. setter(el.name, value);
  184. }
  185. });
  186. const query = {};
  187. const queryParameters = form.querySelectorAll('input[data-component=query]');
  188. queryParameters.forEach(el => {
  189. if (el.type !== 'radio' || (el.type === 'radio' && el.checked)) {
  190. if (el.value === '') {
  191. // Don't include empty values in the request
  192. return;
  193. }
  194. _.set(query, el.name, el.value);
  195. }
  196. });
  197. let path = form.dataset.path;
  198. const urlParameters = form.querySelectorAll('input[data-component=url]');
  199. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  200. const headers = Object.fromEntries(Array.from(form.querySelectorAll('input[data-component=header]'))
  201. .map(el => [el.name, el.value]));
  202. // When using FormData, the browser sets the correct content-type + boundary
  203. let method = form.dataset.method;
  204. if (body instanceof FormData) {
  205. delete headers['Content-Type'];
  206. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  207. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  208. method = 'POST';
  209. setter('_method', form.dataset.method);
  210. }
  211. }
  212. let preflightPromise = Promise.resolve();
  213. if (window.useCsrf && window.csrfUrl) {
  214. preflightPromise = makeAPICall('GET', window.csrfUrl).then(() => {
  215. headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
  216. });
  217. }
  218. return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
  219. .then(([responseStatus, statusText, responseContent, responseHeaders]) => {
  220. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  221. })
  222. .catch(err => {
  223. if (err.name === "AbortError") {
  224. console.log("Request cancelled");
  225. return;
  226. }
  227. console.log("Error while making request: ", err);
  228. handleError(endpointId, err);
  229. })
  230. .finally(() => {
  231. executeBtn.disabled = false;
  232. executeBtn.textContent = executeBtn.dataset.initialText;
  233. });
  234. }