tryitout.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. document.querySelectorAll(`label[id^=auth-] > input`)
  6. .forEach(el => {
  7. el.addEventListener('change', (event) => {
  8. window.lastAuthValue = event.target.value;
  9. document.querySelectorAll(`label[id^=auth-] > input`)
  10. .forEach(otherInput => {
  11. if (otherInput === el) return;
  12. // Don't block the main thread
  13. setTimeout(() => {
  14. otherInput.value = window.lastAuthValue;
  15. }, 0);
  16. });
  17. });
  18. });
  19. }
  20. window.addEventListener('DOMContentLoaded', cacheAuthValue);
  21. function getCookie(name) {
  22. if (!document.cookie) {
  23. return null;
  24. }
  25. const cookies = document.cookie.split(';')
  26. .map(c => c.trim())
  27. .filter(c => c.startsWith(name + '='));
  28. if (cookies.length === 0) {
  29. return null;
  30. }
  31. return decodeURIComponent(cookies[0].split('=')[1]);
  32. }
  33. function tryItOut(endpointId) {
  34. document.querySelector(`#btn-tryout-${endpointId}`).hidden = true;
  35. document.querySelector(`#btn-executetryout-${endpointId}`).hidden = false;
  36. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = false;
  37. // Show all input fields
  38. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  39. .forEach(el => el.hidden = false);
  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 = "Send Request 💥";
  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.hidden = true);
  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) {
  72. console.log({endpointId, path, body, query, headers});
  73. if (!(body instanceof FormData)) {
  74. body = JSON.stringify(body)
  75. }
  76. const url = new URL(window.baseUrl + '/' + 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.baseUrl,
  103. mode: 'cors',
  104. credentials: 'same-origin',
  105. })
  106. .then(response => Promise.all([response.status, 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 === '' ? '<Empty response>' : response;
  128. isJson && window.hljs.highlightBlock(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. errorMessage += "\n\nTip: Check that you're properly connected to the network.";
  141. errorMessage += "\nIf you're a maintainer of ths API, verify that your API is running and you've enabled CORS.";
  142. errorMessage += "\nYou can check the Dev Tools console for debugging information.";
  143. document.querySelector('#execution-error-message-' + endpointId).textContent = errorMessage;
  144. const errorEl = document.querySelector('#execution-error-' + endpointId);
  145. errorEl.hidden = false;
  146. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  147. }
  148. async function executeTryOut(endpointId, form) {
  149. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  150. executeBtn.textContent = "⏱ Sending...";
  151. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  152. let body;
  153. let setter;
  154. if (form.dataset.hasfiles === "1") {
  155. body = new FormData();
  156. setter = (name, value) => body.append(name, value);
  157. } else if (form.dataset.isarraybody === "1") {
  158. body = [];
  159. setter = (name, value) => _.set(body, name, value);
  160. } else {
  161. body = {};
  162. setter = (name, value) => _.set(body, name, value);
  163. }
  164. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  165. bodyParameters.forEach(el => {
  166. let value = el.value;
  167. if (el.type === 'file' && el.files[0]) {
  168. setter(el.name, el.files[0]);
  169. return;
  170. }
  171. if (el.type !== 'radio') {
  172. if (value === "" && el.required === false) {
  173. // Don't include empty optional values in the request
  174. return;
  175. }
  176. setter(el.name, value);
  177. return;
  178. }
  179. if (el.checked) {
  180. value = (value === 'false') ? false : true;
  181. setter(el.name, value);
  182. }
  183. });
  184. const query = {};
  185. const queryParameters = form.querySelectorAll('input[data-component=query]');
  186. queryParameters.forEach(el => {
  187. if (el.type !== 'radio' || (el.type === 'radio' && el.checked)) {
  188. if (el.value === '' && el.required === false) {
  189. // Don't include empty optional values in the request
  190. return;
  191. }
  192. _.set(query, el.name, el.value);
  193. }
  194. });
  195. let path = form.dataset.path;
  196. const urlParameters = form.querySelectorAll('input[data-component=url]');
  197. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  198. const headers = JSON.parse(form.dataset.headers);
  199. // Check for auth param that might go in header
  200. if (form.dataset.authed === "1") {
  201. const authHeaderEl = form.querySelector('input[data-component=header]');
  202. if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
  203. }
  204. // When using FormData, the browser sets the correct content-type + boundary
  205. let method = form.dataset.method;
  206. if (body instanceof FormData) {
  207. delete headers['Content-Type'];
  208. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  209. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  210. method = 'POST';
  211. setter('_method', form.dataset.method);
  212. }
  213. }
  214. let preflightPromise = Promise.resolve();
  215. if (window.useCsrf && window.csrfUrl) {
  216. preflightPromise = makeAPICall('GET', window.csrfUrl, {}, {}, {}, null).then(() => {
  217. headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
  218. });
  219. }
  220. return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
  221. .then(([responseStatus, responseContent, responseHeaders]) => {
  222. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  223. })
  224. .catch(err => {
  225. if (err.name === "AbortError") {
  226. console.log("Request cancelled");
  227. return;
  228. }
  229. console.log("Error while making request: ", err);
  230. handleError(endpointId, err);
  231. })
  232. .finally(() => {
  233. executeBtn.textContent = "Send Request 💥";
  234. });
  235. }