tryitout.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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-executetryout-${endpointId}`).hidden = false;
  35. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = false;
  36. // Show all input fields
  37. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  38. .forEach(el => el.hidden = false);
  39. if (document.querySelector(`#form-${endpointId}`).dataset.authed === "1") {
  40. const authElement = document.querySelector(`#auth-${endpointId}`);
  41. authElement && (authElement.hidden = false);
  42. }
  43. // Expand all nested fields
  44. document.querySelectorAll(`#form-${endpointId} details`)
  45. .forEach(el => el.open = true);
  46. }
  47. function cancelTryOut(endpointId) {
  48. if (window.abortControllers[endpointId]) {
  49. window.abortControllers[endpointId].abort();
  50. delete window.abortControllers[endpointId];
  51. }
  52. document.querySelector(`#btn-tryout-${endpointId}`).hidden = false;
  53. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  54. executeBtn.hidden = true;
  55. executeBtn.textContent = "Send Request 💥";
  56. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = true;
  57. // Hide inputs
  58. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  59. .forEach(el => el.hidden = true);
  60. document.querySelectorAll(`#form-${endpointId} details`)
  61. .forEach(el => el.open = false);
  62. const authElement = document.querySelector(`#auth-${endpointId}`);
  63. authElement && (authElement.hidden = true);
  64. document.querySelector('#execution-results-' + endpointId).hidden = true;
  65. document.querySelector('#execution-error-' + endpointId).hidden = true;
  66. // Revert to sample code blocks
  67. document.querySelector('#example-requests-' + endpointId).hidden = false;
  68. document.querySelector('#example-responses-' + endpointId).hidden = false;
  69. }
  70. function makeAPICall(method, path, body = {}, query = {}, headers = {}, endpointId = null) {
  71. console.log({endpointId, path, body, query, headers});
  72. if (!(body instanceof FormData) && typeof body !== "string") {
  73. body = JSON.stringify(body)
  74. }
  75. const url = new URL(window.baseUrl + '/' + path.replace(/^\//, ''));
  76. // We need this function because if you try to set an array or object directly to a URLSearchParams object,
  77. // you'll get [object Object] or the array.toString()
  78. function addItemToSearchParamsObject(key, value, searchParams) {
  79. if (Array.isArray(value)) {
  80. value.forEach((v, i) => {
  81. // Append {filters: [first, second]} as filters[0]=first&filters[1]second
  82. addItemToSearchParamsObject(key + '[' + i + ']', v, searchParams);
  83. })
  84. } else if (typeof value === 'object' && value !== null) {
  85. Object.keys(value).forEach((i) => {
  86. // Append {filters: {name: first}} as filters[name]=first
  87. addItemToSearchParamsObject(key + '[' + i + ']', value[i], searchParams);
  88. });
  89. } else {
  90. searchParams.append(key, value);
  91. }
  92. }
  93. Object.keys(query)
  94. .forEach(key => addItemToSearchParamsObject(key, query[key], url.searchParams));
  95. window.abortControllers[endpointId] = new AbortController();
  96. return fetch(url, {
  97. method,
  98. headers,
  99. body: method === 'GET' ? undefined : body,
  100. signal: window.abortControllers[endpointId].signal,
  101. referrer: window.baseUrl,
  102. mode: 'cors',
  103. credentials: 'same-origin',
  104. })
  105. .then(response => Promise.all([response.status, response.statusText, response.text(), response.headers]));
  106. }
  107. function hideCodeSamples(endpointId) {
  108. document.querySelector('#example-requests-' + endpointId).hidden = true;
  109. document.querySelector('#example-responses-' + endpointId).hidden = true;
  110. }
  111. function handleResponse(endpointId, response, status, headers) {
  112. hideCodeSamples(endpointId);
  113. // Hide error views
  114. document.querySelector('#execution-error-' + endpointId).hidden = true;
  115. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  116. // Prettify it if it's JSON
  117. let isJson = false;
  118. try {
  119. const jsonParsed = JSON.parse(response);
  120. if (jsonParsed !== null) {
  121. isJson = true;
  122. response = JSON.stringify(jsonParsed, null, 4);
  123. }
  124. } catch (e) {
  125. }
  126. responseContentEl.textContent = response === '' ? '<Empty response>' : response;
  127. isJson && window.hljs.highlightBlock(responseContentEl);
  128. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  129. statusEl.textContent = ` (${status})`;
  130. document.querySelector('#execution-results-' + endpointId).hidden = false;
  131. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  132. }
  133. function handleError(endpointId, err) {
  134. hideCodeSamples(endpointId);
  135. // Hide response views
  136. document.querySelector('#execution-results-' + endpointId).hidden = true;
  137. // Show error views
  138. let errorMessage = err.message || err;
  139. errorMessage += "\n\nTip: Check that you're properly connected to the network.";
  140. errorMessage += "\nIf you're a maintainer of ths API, verify that your API is running and you've enabled CORS.";
  141. errorMessage += "\nYou can check the Dev Tools console for debugging information.";
  142. document.querySelector('#execution-error-message-' + endpointId).textContent = errorMessage;
  143. const errorEl = document.querySelector('#execution-error-' + endpointId);
  144. errorEl.hidden = false;
  145. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  146. }
  147. async function executeTryOut(endpointId, form) {
  148. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  149. executeBtn.textContent = "⏱ Sending...";
  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 === '' && el.required === false) {
  188. // Don't include empty optional 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 = JSON.parse(form.dataset.headers);
  198. // Check for auth param that might go in header
  199. if (form.dataset.authed === "1") {
  200. const authHeaderEl = form.querySelector('input[data-component=header]');
  201. if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
  202. }
  203. // When using FormData, the browser sets the correct content-type + boundary
  204. let method = form.dataset.method;
  205. if (body instanceof FormData) {
  206. delete headers['Content-Type'];
  207. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  208. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  209. method = 'POST';
  210. setter('_method', form.dataset.method);
  211. }
  212. }
  213. let preflightPromise = Promise.resolve();
  214. if (window.useCsrf && window.csrfUrl) {
  215. preflightPromise = makeAPICall('GET', window.csrfUrl).then(() => {
  216. headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
  217. });
  218. }
  219. return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
  220. .then(([responseStatus, statusText, responseContent, responseHeaders]) => {
  221. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  222. })
  223. .catch(err => {
  224. if (err.name === "AbortError") {
  225. console.log("Request cancelled");
  226. return;
  227. }
  228. console.log("Error while making request: ", err);
  229. handleError(endpointId, err);
  230. })
  231. .finally(() => {
  232. executeBtn.textContent = "Send Request 💥";
  233. });
  234. }