SwaggerUIBundle :指定基本 url

Orw*_*wel 2 swagger-ui

我需要测试一个 api,其中:

接口地址 http://api.mydomain.loc:20109/v1/
API定义网址 http://api.mydomain.loc:20109/v1/swagger/swagger.json

API 定义是:

{
  "openapi": "3.0.1",
  "info": {
    "title": "***",
    "description": "***",
    "version": "v1"
  },
  "servers": [
    {
      "url": "/v1/path1/path2"
    }
  ],
  "/ressource1": {
      "get": {
        "responses": {
          "200": {
            "description": "Success"
          }
        }
      }
    },
  ...
}
Run Code Online (Sandbox Code Playgroud)

我按照文档中的 unpkg 部分启动本地 Swagger UI。我使用以下内容创建文件“swagger-ui.html”:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta
    name="description"
    content="SwaggerIU"
  />
  <title>SwaggerUI</title>
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js" crossorigin></script>
<script>
  window.onload = () => {
    window.ui = SwaggerUIBundle({
      url: 'http://api.mydomain.loc:20109/v1/swagger/swagger.json',
      dom_id: '#swagger-ui',
    });
  };
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我打开页面时,API 定义已正确加载并显示 Swagger UI。但是当我尝试端点“ressource1”时,Swagger UI 调用“http://api.mydomain.loc:20109/v1/path1/path2/ressource1”。就我而言,我想调用“http://api.mydomain.loc:20109/v1/ressource1”。

如何使用 unpkg 覆盖 Swagger UI 中的基本路径?

Hel*_*len 5

这是另一个使用插件的解决方案rootInjects主要思想与@vernou 的答案相同- 动态更新 OpenAPI 定义。

<!-- index.html -->

<script>
const UrlMutatorPlugin = (system) => ({
  rootInjects: {
    setServer: (server) => {
      const jsonSpec = system.getState().toJSON().spec.json;
      const servers = [{url: server}];
      const newJsonSpec = Object.assign({}, jsonSpec, { servers });

      return system.specActions.updateJsonSpec(newJsonSpec);
    }
  }
});

window.onload = function() {
  const ui = SwaggerUIBundle({
    url: "http://api.mydomain.loc:20109/v1/swagger/swagger.json",
    ...

    // Add UrlMutatorPlugin to the plugins list
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl,
      UrlMutatorPlugin
    ],

    // This will set appropriate data when Swagger UI is ready
    onComplete: () => {
      window.ui.setServer("http://api.mydomain.loc:20109/v1")
    } 
  });

  window.ui = ui;
};
</script>

Run Code Online (Sandbox Code Playgroud)