在运行时更改 swagger-ui 服务器变量

Changing swagger-ui server variable at runtime

使用 openapi v3 配置我有一个名为 'hostname' 的服务器变量,用于 build url,例如:

...
servers:
- url: http://{hostname}/api
 variables:
  hostname:
   "default": "some default here"
....

在运行时我希望能够更改 'hostname' 服务器变量。我在页面上找到了 UI 元素,

<input type="text" value="some default here" data-variable="hostname">

通过编辑输入字段更改变量工作正常,但通过 jQuery 更改输入字段无效,即使在设置值后触发 "change" 事件,值恢复展开 api 部分之一时。我还尝试触发 keyup/keydown 和 focusin/focusout 事件以更好地模拟用户如何更改字段。

是否有更大胆的-ui方法来通过公开调用更改此值?我已经浏览过 window.ui 但它有点神秘。

I have an api.yaml file hosted on different IoT devices. Each device will have a different hostname based on its configuration. When the page is loaded I'm trying to use javascript to set the 'hostname' server variable to be window.location.hostname, for example via javascript.

您可以简单地指定一个相对服务器 url – 它将相对于 OpenAPI 定义文件的位置进行解析。

例如,如果您有

servers:
  - url: /api

并且 API 定义文件位于

http://foobar/spec/api.yaml

然后 API 调用的基础 url 将解析为

http://foobar/api

您可以在渲染之前通过编写插件更改规范 json

const ui = SwaggerUI({
    // ...
    plugins: [
        // add a plugin to alter spec before it rendered
        {
            statePlugins: {
                spec: {
                    wrapActions: {
                        updateJsonSpec: function(oriAction, system) {
                            return (spec) => {
                                // change spec.servers here to add new entry, use concat to put it as the first & default one
                                spec.servers = [{url: someDynamicUrlInRuntime}].concat(spec.servers || [])
                                return oriAction(spec)
                            }
                        }
                    }
                }
            }
        }
    ]
    // ...
})

调整 for use with SwaggerUIBundle as used in the index.html from swagger-ui

plugins: [
  SwaggerUIBundle.plugins.DownloadUrl,

  // Custom plugin that replaces the server list with the current url
  function() {
    return {
      statePlugins: {
        spec: {
          wrapActions: {
            updateJsonSpec: function(oriAction, system) {
              return (spec) => {
                    spec.servers = [{url: window.location.origin}]
                    return oriAction(spec)
              }
            }
          }
        }
      }
    }
  }
],

这样 index.html 可以从后端服务本身提供服务,并且只会引用它自己 url。