tryitout.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. referrer: window.baseUrl,
  84. mode: 'cors',
  85. credentials: 'same-origin',
  86. })
  87. .then(response => Promise.all([response.status, response.text(), response.headers]));
  88. }
  89. function hideCodeSamples(endpointId) {
  90. document.querySelector('#example-requests-' + endpointId).hidden = true;
  91. document.querySelector('#example-responses-' + endpointId).hidden = true;
  92. }
  93. function handleResponse(endpointId, response, status, headers) {
  94. hideCodeSamples(endpointId);
  95. // Hide error views
  96. document.querySelector('#execution-error-' + endpointId).hidden = true;
  97. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  98. // Prettify it if it's JSON
  99. let isJson = false;
  100. try {
  101. const jsonParsed = JSON.parse(response);
  102. if (jsonParsed !== null) {
  103. isJson = true;
  104. response = JSON.stringify(jsonParsed, null, 4);
  105. }
  106. } catch (e) {
  107. }
  108. responseContentEl.textContent = response === '' ? '<Empty response>' : response;
  109. isJson && window.hljs.highlightBlock(responseContentEl);
  110. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  111. statusEl.textContent = ` (${status})`;
  112. document.querySelector('#execution-results-' + endpointId).hidden = false;
  113. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  114. }
  115. function handleError(endpointId, err) {
  116. hideCodeSamples(endpointId);
  117. // Hide response views
  118. document.querySelector('#execution-results-' + endpointId).hidden = true;
  119. // Show error views
  120. let errorMessage = err.message || err;
  121. errorMessage += "\n\nTip: Check that you're properly connected to the network.";
  122. errorMessage += "\nIf you're a maintainer of ths API, verify that your API is running and you've enabled CORS.";
  123. errorMessage += "\nYou can check the Dev Tools console for debugging information.";
  124. document.querySelector('#execution-error-message-' + endpointId).textContent = errorMessage;
  125. const errorEl = document.querySelector('#execution-error-' + endpointId);
  126. errorEl.hidden = false;
  127. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  128. }
  129. async function executeTryOut(endpointId, form) {
  130. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  131. executeBtn.textContent = "⏱ Sending...";
  132. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  133. let body;
  134. let setter;
  135. if (form.dataset.hasfiles === "1") {
  136. body = new FormData();
  137. setter = (name, value) => body.append(name, value);
  138. } else if (form.dataset.isarraybody === "1") {
  139. body = [];
  140. setter = (name, value) => _.set(body, name, value);
  141. } else {
  142. body = {};
  143. setter = (name, value) => _.set(body, name, value);
  144. }
  145. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  146. bodyParameters.forEach(el => {
  147. let value = el.value;
  148. if (el.type === 'file' && el.files[0]) {
  149. setter(el.name, el.files[0]);
  150. return;
  151. }
  152. if (el.type !== 'radio') {
  153. if (value === "" && el.required === false) {
  154. // Don't include empty optional values in the request
  155. return;
  156. }
  157. setter(el.name, value);
  158. return;
  159. }
  160. if (el.checked) {
  161. value = (value === 'false') ? false : true;
  162. setter(el.name, value);
  163. }
  164. });
  165. const query = {};
  166. const queryParameters = form.querySelectorAll('input[data-component=query]');
  167. queryParameters.forEach(el => {
  168. if (el.type !== 'radio' || (el.type === 'radio' && el.checked)) {
  169. _.set(query, el.name, el.value);
  170. }
  171. });
  172. let path = form.dataset.path;
  173. const urlParameters = form.querySelectorAll('input[data-component=url]');
  174. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  175. const headers = JSON.parse(form.dataset.headers);
  176. // Check for auth param that might go in header
  177. if (form.dataset.authed === "1") {
  178. const authHeaderEl = form.querySelector('input[data-component=header]');
  179. if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
  180. }
  181. // When using FormData, the browser sets the correct content-type + boundary
  182. let method = form.dataset.method;
  183. if (body instanceof FormData) {
  184. delete headers['Content-Type'];
  185. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  186. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  187. method = 'POST';
  188. setter('_method', form.dataset.method);
  189. }
  190. }
  191. const preflightPromise = window.useCsrf && window.csrfUrl ? makeAPICall('GET', window.csrfUrl, {}, {}, {}, null).then(() => {
  192. headers['X-XSRF-TOKEN'] = getCookie(window.csrfCookieName);
  193. return makeAPICall(method, path, body, query, headers, endpointId);
  194. }) : makeAPICall(method, path, body, query, headers, endpointId);
  195. preflightPromise
  196. .then(([responseStatus, responseContent, responseHeaders]) => {
  197. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  198. })
  199. .catch(err => {
  200. if (err.name === "AbortError") {
  201. console.log("Request cancelled");
  202. return;
  203. }
  204. console.log("Error while making request: ", err);
  205. handleError(endpointId, err);
  206. })
  207. .finally(() => {
  208. executeBtn.textContent = "Send Request 💥";
  209. });
  210. }