redoc-init.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // redoc-init.js
  2. // https://github.com/axnsan12/drf-yasg
  3. // Copyright 2017 - 2021, Cristian V. <cristi@cvjd.me>
  4. // This file is licensed under the BSD 3-Clause License.
  5. // License text available at https://opensource.org/licenses/BSD-3-Clause
  6. "use strict";
  7. var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
  8. var specURL = currentPath + '?format=openapi';
  9. var redoc = document.createElement("redoc");
  10. var redocSettings = JSON.parse(document.getElementById('redoc-settings').innerHTML);
  11. if (redocSettings.url) {
  12. specURL = redocSettings.url;
  13. }
  14. delete redocSettings.url;
  15. if (redocSettings.fetchSchemaWithQuery) {
  16. var query = new URLSearchParams(window.location.search || '').entries();
  17. var url = specURL.split('?');
  18. var usp = new URLSearchParams(url[1] || '');
  19. for (var it = query.next(); !it.done; it = query.next()) {
  20. usp.set(it.value[0], it.value[1]);
  21. }
  22. url[1] = usp.toString();
  23. specURL = url[1] ? url.join('?') : url[0];
  24. }
  25. delete redocSettings.fetchSchemaWithQuery;
  26. redoc.setAttribute("spec-url", specURL);
  27. function camelToKebab(str) {
  28. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  29. }
  30. for (var p in redocSettings) {
  31. if (redocSettings.hasOwnProperty(p)) {
  32. if (redocSettings[p] !== null && redocSettings[p] !== undefined && redocSettings[p] !== false) {
  33. redoc.setAttribute(camelToKebab(p), redocSettings[p].toString());
  34. }
  35. }
  36. }
  37. document.body.replaceChild(redoc, document.getElementById('redoc-placeholder'));
  38. function hideEmptyVersion() {
  39. // 'span.api-info-version' is for redoc 1.x, 'div.api-info span' is for redoc 2-alpha
  40. var apiVersion = document.querySelector('span.api-info-version') || document.querySelector('div.api-info span');
  41. if (!apiVersion) {
  42. console.log("WARNING: could not find API versionString element (span.api-info-version)");
  43. return;
  44. }
  45. var versionString = apiVersion.innerText;
  46. if (versionString) {
  47. // trim spaces and surrounding ()
  48. versionString = versionString.replace(/ /g, '');
  49. versionString = versionString.replace(/(^\()|(\)$)/g, '');
  50. }
  51. if (!versionString) {
  52. // hide version element if empty
  53. apiVersion.classList.add("hidden");
  54. }
  55. }
  56. if (document.querySelector('span.api-info-version') || document.querySelector('div.api-info span')) {
  57. hideEmptyVersion();
  58. }
  59. else {
  60. insertionQ('span.api-info-version').every(hideEmptyVersion);
  61. insertionQ('div.api-info span').every(hideEmptyVersion);
  62. }