summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/swagger.js
blob: fcdab18c62337c87f2cd2497e10c81428f8fc78c (plain)
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
import { SwaggerUIBundle } from 'swagger-ui-dist';
import { safeLoad } from 'js-yaml';
import { isObject } from '~/lib/utils/type_utility';
import { getParameterByName } from '~/lib/utils/url_utility';
import { resetServiceWorkersPublicPath } from '~/lib/utils/webpack';

const resetWebpackPublicPath = () => {
  window.gon = { relative_url_root: getParameterByName('relativeRootPath') };
  resetServiceWorkersPublicPath();
};

const renderSwaggerUI = (value) => {
  /* SwaggerUIBundle accepts openapi definition
   * in only JSON format, so we convert the YAML
   * config to JSON if it's not JSON value
   */
  let spec = value;
  if (!isObject(spec)) {
    spec = safeLoad(spec, { json: true });
  }

  resetWebpackPublicPath();

  Promise.all([import(/* webpackChunkName: 'openapi' */ 'swagger-ui-dist/swagger-ui.css')])
    .then(() => {
      SwaggerUIBundle({
        spec,
        dom_id: '#swagger-ui',
        deepLinking: true,
        displayOperationId: true,
      });
    })
    .catch((error) => {
      throw error;
    });
};

const addInitHook = () => {
  window.addEventListener(
    'message',
    (event) => {
      if (event.origin !== window.location.origin) {
        return;
      }
      renderSwaggerUI(event.data);
    },
    false,
  );
};

addInitHook();
export default {};