tryitout.js 9.9 KB

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