All files / app/assets/javascripts/blob/openapi index.js

85% Statements 17/20
57.14% Branches 4/7
75% Functions 3/4
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                    2x   2x 3x 3x 3x 3x   3x       3x     2x 3x   3x                 3x       3x 3x   3x   3x   3x        
import SwaggerClient from 'swagger-client';
import { setAttributes } from '~/lib/utils/dom_utils';
import {
  getBaseURL,
  relativePathToAbsolute,
  joinPaths,
  setUrlParams,
  getParameterByName,
} from '~/lib/utils/url_utility';
 
const SANDBOX_FRAME_PATH = '/-/sandbox/swagger';
 
const getSandboxFrameSrc = () => {
  const path = joinPaths(gon.relative_url_root || '', SANDBOX_FRAME_PATH);
  const absoluteUrl = relativePathToAbsolute(path, getBaseURL());
  const displayOperationId = getParameterByName('displayOperationId');
  const params = { displayOperationId };
 
  Iif (window.gon?.relative_url_root) {
    params.relativeRootPath = window.gon.relative_url_root;
  }
 
  return setUrlParams(params, absoluteUrl);
};
 
const createSandbox = () => {
  const iframeEl = document.createElement('iframe');
 
  setAttributes(iframeEl, {
    src: getSandboxFrameSrc(),
    sandbox: 'allow-scripts allow-popups allow-forms',
    frameBorder: 0,
    width: '100%',
    // The height will be adjusted dynamically.
    // Follow-up issue: https://gitlab.com/gitlab-org/gitlab/-/issues/377969
    height: '1000',
  });
  return iframeEl;
};
 
export default async (el = document.getElementById('js-openapi-viewer')) => {
  const wrapperEl = el;
  const sandboxEl = createSandbox();
 
  const { spec } = await SwaggerClient.resolve({ url: wrapperEl.dataset.endpoint });
 
  wrapperEl.appendChild(sandboxEl);
 
  sandboxEl.addEventListener('load', () => {
    if (spec) sandboxEl.contentWindow.postMessage(JSON.stringify(spec), '*');
  });
};