未验证 提交 31a8b137 编写于 作者: K kyle 提交者: GitHub

feature: full-spectrum runtime Docker configuration (via #4965)

* reorganize docker things

* Configurator WIP

* implement Docker runtime config generator

* add tests

* update documentation

* fix Markdown tables

* Move Docker section

* add note to README

* move up `nodejs` install for more aggressive caching

* drop exclusive test

* fix missing `DISPLAY_OPERATION_ID`
上级 b9300211
......@@ -5,3 +5,4 @@
/src
/swagger-ui-dist-package
/test
/node_modules
\ No newline at end of file
# Looking for information on environment variables?
# We don't declare them here — take a look at our docs.
# https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md
FROM nginx:1.15-alpine
RUN apk add nodejs
LABEL maintainer="fehguy"
ENV VERSION "v2.2.10"
ENV FOLDER "swagger-ui-2.2.10"
ENV API_URL "https://petstore.swagger.io/v2/swagger.json"
ENV API_URLS ""
ENV API_KEY "**None**"
ENV OAUTH_CLIENT_ID "**None**"
ENV OAUTH_CLIENT_SECRET "**None**"
......@@ -15,16 +17,16 @@ ENV OAUTH_ADDITIONAL_PARAMS "**None**"
ENV SWAGGER_JSON "/app/swagger.json"
ENV PORT 8080
ENV BASE_URL ""
ENV CONFIG_URL ""
COPY nginx.conf /etc/nginx/
COPY ./docker/nginx.conf /etc/nginx/
# copy swagger files to the `/js` folder
COPY ./dist/* /usr/share/nginx/html/
COPY ./docker-run.sh /usr/share/nginx/
COPY ./docker/run.sh /usr/share/nginx/
COPY ./docker/configurator /usr/share/nginx/configurator
RUN chmod +x /usr/share/nginx/docker-run.sh
RUN chmod +x /usr/share/nginx/run.sh
EXPOSE 8080
CMD ["sh", "/usr/share/nginx/docker-run.sh"]
CMD ["sh", "/usr/share/nginx/run.sh"]
......@@ -37,8 +37,7 @@
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Build a system
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
......@@ -52,6 +51,7 @@
],
layout: "StandaloneLayout"
})
// End Swagger UI call region
window.ui = ui
}
......
const fs = require("fs")
const path = require("path")
const translator = require("./translator")
const configSchema = require("./variables")
const START_MARKER = "// Begin Swagger UI call region"
const END_MARKER = "// End Swagger UI call region"
const targetPath = path.normalize(process.cwd() + "/" + process.argv[2])
const originalHtmlContent = fs.readFileSync(targetPath, "utf8")
const startMarkerIndex = originalHtmlContent.indexOf(START_MARKER)
const endMarkerIndex = originalHtmlContent.indexOf(END_MARKER)
const beforeStartMarkerContent = originalHtmlContent.slice(0, startMarkerIndex)
const afterEndMarkerContent = originalHtmlContent.slice(endMarkerIndex + END_MARKER.length)
fs.writeFileSync(targetPath, `${beforeStartMarkerContent}
${START_MARKER}
const ui = SwaggerUIBundle({
${indent(translator(process.env, { injectBaseConfig: true }), 8, 2)}
})
${END_MARKER}
${afterEndMarkerContent}`)
function indent(str, len, fromLine) {
return str
.split("\n")
.map((line, i) => {
if(i + 1 >= fromLine) {
return `${Array(len + 1).join(" ")}${line}`
} else {
return line
}
})
.join("\n")
}
\ No newline at end of file
// Converts an object of environment variables into a Swagger UI config object
const configSchema = require("./variables")
const baseConfig = {
url: {
value: "https://petstore.swagger.io/v2/swagger.json",
schema: {
type: "string"
}
},
dom_id: {
value: "#swagger-ui",
schema: {
type: "string"
}
},
deepLinking: {
value: "true",
schema: {
type: "boolean"
}
},
presets: {
value: `[\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n]`,
schema: {
type: "array"
}
},
plugins: {
value: `[\n SwaggerUIBundle.plugins.DownloadUrl\n]`,
schema: {
type: "array"
}
},
layout: {
value: "StandaloneLayout",
schema: {
type: "string"
}
}
}
function objectToKeyValueString(env, { injectBaseConfig = false, schema = configSchema } = {}) {
let valueStorage = injectBaseConfig ? Object.assign({}, baseConfig) : {}
const keys = Object.keys(env)
// Compute an intermediate representation that holds candidate values and schemas.
//
// This is useful for deduping between multiple env keys that set the same
// config variable.
keys.forEach(key => {
const varSchema = schema[key]
const value = env[key]
if(!varSchema) return
const storageContents = valueStorage[varSchema.name]
if(storageContents) {
if(varSchema.legacy === true) {
// If we're looking at a legacy var, it should lose out to any already-set value
return
}
delete valueStorage[varSchema.name]
}
valueStorage[varSchema.name] = {
value,
schema: varSchema
}
})
// Compute a key:value string based on valueStorage's contents.
let result = ""
Object.keys(valueStorage).forEach(key => {
const value = valueStorage[key]
const escapedName = /[^a-zA-Z0-9]/.test(key) ? `"${key}"` : key
if (value.schema.type === "string") {
result += `${escapedName}: "${value.value}",\n`
} else {
result += `${escapedName}: ${value.value === "" ? `undefined` : value.value},\n`
}
})
return result.trim()
}
module.exports = objectToKeyValueString
\ No newline at end of file
const standardVariables = {
CONFIG_URL: {
type: "string",
name: "configUrl"
},
DOM_ID: {
type: "string",
name: "dom_id"
},
SPEC: {
type: "object",
name: "spec"
},
URL: {
type: "string",
name: "url"
},
URLS: {
type: "array",
name: "urls"
},
URLS_PRIMARY_NAME: {
type: "string",
name: "urls.primaryName"
},
LAYOUT: {
type: "string",
name: "layout"
},
DEEP_LINKING: {
type: "boolean",
name: "deepLinking"
},
DISPLAY_OPERATION_ID: {
type: "boolean",
name: "displayOperationId"
},
DEFAULT_MODELS_EXPAND_DEPTH: {
type: "number",
name: "defaultModelsExpandDepth"
},
DEFAULT_MODEL_EXPAND_DEPTH: {
type: "number",
name: "defaultModelExpandDepth"
},
DEFAULT_MODEL_RENDERING: {
type: "string",
name: "defaultModelRendering"
},
DISPLAY_REQUEST_DURATION: {
type: "boolean",
name: "displayRequestDuration"
},
DOC_EXPANSION: {
type: "string",
name: "docExpansion"
},
FILTER: {
type: "string",
name: "filter"
},
MAX_DISPLAYED_TAGS: {
type: "number",
name: "maxDisplayedTags"
},
SHOW_EXTENSIONS: {
type: "boolean",
name: "showExtensions"
},
SHOW_COMMON_EXTENSIONS: {
type: "boolean",
name: "showCommonExtensions"
},
OAUTH2_REDIRECT_URL: {
type: "string",
name: "oauth2RedirectUrl"
},
SHOW_MUTATED_REQUEST: {
type: "boolean",
name: "showMutatedRequest"
},
SUPPORTED_SUBMIT_METHODS: {
type: "array",
name: "supportedSubmitMethods"
},
VALIDATOR_URL: {
type: "string",
name: "validatorUrl"
}
}
const legacyVariables = {
API_URL: {
type: "string",
name: "url",
legacy: true
},
API_URLS: {
type: "array",
name: "urls",
legacy: true
}
}
module.exports = Object.assign({}, standardVariables, legacyVariables)
\ No newline at end of file
#! /bin/sh
set -e
BASE_URL=${BASE_URL:-/}
NGINX_ROOT=/usr/share/nginx/html
INDEX_FILE=$NGINX_ROOT/index.html
node /usr/share/nginx/configurator $INDEX_FILE
replace_in_index () {
if [ "$1" != "**None**" ]; then
sed -i "s|/\*||g" $INDEX_FILE
......@@ -40,27 +41,6 @@ if [[ -f $SWAGGER_JSON ]]; then
REL_PATH="./$(basename $SWAGGER_JSON)"
sed -i "s|https://petstore.swagger.io/v2/swagger.json|$REL_PATH|g" $INDEX_FILE
sed -i "s|http://example.com/api|$REL_PATH|g" $INDEX_FILE
else
sed -i "s|https://petstore.swagger.io/v2/swagger.json|$API_URL|g" $INDEX_FILE
sed -i "s|http://example.com/api|$API_URL|g" $INDEX_FILE
fi
if [[ -n "$VALIDATOR_URL" ]]; then
sed -i "s|.*validatorUrl:.*$||g" $INDEX_FILE
TMP_VU="$VALIDATOR_URL"
[[ "$VALIDATOR_URL" != "null" && "$VALIDATOR_URL" != "undefined" ]] && TMP_VU="\"${VALIDATOR_URL}\""
sed -i "s|\(url: .*,\)|\1\n validatorUrl: ${TMP_VU},|g" $INDEX_FILE
unset TMP_VU
fi
# replace `url` with `urls` option if API_URLS is set
if [[ -n "$API_URLS" ]]; then
sed -i "s|^\(\s*\)url: .*,|\1urls: $API_URLS,|g" $INDEX_FILE
fi
if [[ -n "$CONFIG_URL" ]]; then
sed -i "s|^\(\s*\)url: .*,|\1configUrl: '$CONFIG_URL',|g" $INDEX_FILE
sed -i "s|^\(\s*\)urls: .*,|\1configUrl: '$CONFIG_URL',|g" $INDEX_FILE
fi
# replace the PORT that nginx listens on if PORT is supplied
......
......@@ -10,7 +10,6 @@ From lowest to highest precedence:
- configuration document fetched from a specified `configUrl`
- configuration items passed as key/value pairs in the URL query string
### Parameters
Parameters with dots in their names are single strings used to organize subordinate parameters, and are not indicative of a nested structure.
......@@ -23,67 +22,127 @@ Type notations are formatted like so:
##### Core
Parameter Name | Description
--- | ---
<a name="configUrl"></a>`configUrl` | `String`. URL to fetch external configuration document from.
<a name="dom_id"></a>`dom_id` |`String`, **REQUIRED** if `domNode` is not provided. The id of a dom element inside which SwaggerUi will put the user interface for swagger.
<a name="domNode"></a>`domNode` | `Element`, **REQUIRED** if `dom_id` is not provided. The HTML DOM element inside which SwaggerUi will put the user interface for swagger. Overrides `dom_id`.
<a name="spec"></a>`spec` | `Object={}`. A JS object describing the OpenAPI Specification. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them.
<a name="url"></a>`url` | `String`. The url pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
<a name="urls"></a>`urls` | `Array`. An array of API definition objects (`[{url: "<url1>", name: "<name1>"},{url: "<url2>", name: "<name2>"}]`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
<a name="urls.primaryName"></a>`urls.primaryName` | `String`. When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger-UI loads, instead of defaulting to the first spec in `urls`.
Parameter name | Docker variable | Description
--- | --- | -----
<a name="configUrl"></a>`configUrl` | `CONFIG_URL` | `String`. URL to fetch external configuration document from.
<a name="dom_id"></a>`dom_id` | `DOM_ID` |`String`, **REQUIRED** if `domNode` is not provided. The id of a dom element inside which SwaggerUi will put the user interface for swagger.
<a name="domNode"></a>`domNode` | _Unavailable_ | `Element`, **REQUIRED** if `dom_id` is not provided. The HTML DOM element inside which SwaggerUi will put the user interface for swagger. Overrides `dom_id`.
<a name="spec"></a>`spec` | `SPEC` | `Object={}`. A JS object describing the OpenAPI Specification. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them.
<a name="url"></a>`url` | `URL` | `String`. The url pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
<a name="urls"></a>`urls` | `URLS` | `Array`. An array of API definition objects (`[{url: "<url1>", name: "<name1>"},{url: "<url2>", name: "<name2>"}]`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
<a name="urls.primaryName"></a>`urls.primaryName` | `URLS_PRIMARY_NAME` | `String`. When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger-UI loads, instead of defaulting to the first spec in `urls`.
##### Plugin system
Read more about the plugin system in the [Customization documentation](/docs/customization/overview.md).
Parameter Name | Description
--- | ---
<a name="layout"></a>`layout` | `String="BaseLayout"`. The name of a component available via the plugin system to use as the top-level layout for Swagger-UI.
<a name="plugins"></a>`plugins` | `Array=[]`. An array of plugin functions to use in Swagger-UI.
<a name="presets"></a>`presets` | `Array=[SwaggerUI.presets.ApisPreset]`. An array of presets to use in Swagger-UI. Usually, you'll want to include `ApisPreset` if you use this option.
Parameter name | Docker variable | Description
--- | --- | -----
<a name="layout"></a>`layout` | _Unavailable_ | `String="BaseLayout"`. The name of a component available via the plugin system to use as the top-level layout for Swagger-UI.
<a name="plugins"></a>`plugins` | _Unavailable_ | `Array=[]`. An array of plugin functions to use in Swagger-UI.
<a name="presets"></a>`presets` | _Unavailable_ | `Array=[SwaggerUI.presets.ApisPreset]`. An array of presets to use in Swagger-UI. Usually, you'll want to include `ApisPreset` if you use this option.
##### Display
Parameter Name | Description
--- | ---
<a name="deepLinking"></a>`deepLinking` | `Boolean=false`. If set to `true`, enables deep linking for tags and operations. See the [Deep Linking documentation](/docs/usage/deep-linking.md) for more information.
<a name="displayOperationId"></a>`displayOperationId` | `Boolean=false`. Controls the display of operationId in operations list. The default is `false`.
<a name="defaultModelsExpandDepth"></a>`defaultModelsExpandDepth` | `Number=1`. The default expansion depth for models (set to -1 completely hide the models).
<a name="defaultModelExpandDepth"></a>`defaultModelExpandDepth` | `Number=1`. The default expansion depth for the model on the model-example section.
<a name="defaultModelRendering"></a>`defaultModelRendering` | `String=["example"*, "model"]`. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)
<a name="displayRequestDuration"></a>`displayRequestDuration` | `Boolean=false`. Controls the display of the request duration (in milliseconds) for Try-It-Out requests.
<a name="docExpansion"></a>`docExpansion` | `String=["list"*, "full", "none"]`. Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing).
<a name="filter"></a>`filter` | `Boolean=false OR String`. If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be Boolean to enable or disable, or a string, in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag.
<a name="maxDisplayedTags"></a>`maxDisplayedTags` | `Number`. If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations.
<a name="operationsSorter"></a>`operationsSorter` | `Function=(a => a)`. Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.
<a name="showExtensions"></a>`showExtensions` | `Boolean=false`. Controls the display of vendor extension (`x-`) fields and values for Operations, Parameters, and Schema.
<a name="showCommonExtensions"></a>`showCommonExtensions` | `Boolean=false`. Controls the display of extensions (`pattern`, `maxLength`, `minLength`, `maximum`, `minimum`) fields and values for Parameters.
<a name="tagSorter"></a>`tagsSorter` | `Function=(a => a)`. Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function (see [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger-UI.
<a name="onComplete"></a>`onComplete` | `Function=NOOP`. Provides a mechanism to be notified when Swagger-UI has finished rendering a newly provided definition.
Parameter name | Docker variable | Description
--- | --- | -----
<a name="deepLinking"></a>`deepLinking` | `DEEP_LINKING` | `Boolean=false`. If set to `true`, enables deep linking for tags and operations. See the [Deep Linking documentation](/docs/usage/deep-linking.md) for more information.
<a name="displayOperationId"></a>`displayOperationId` | `DISPLAY_OPERATION_ID` | `Boolean=false`. Controls the display of operationId in operations list. The default is `false`.
<a name="defaultModelsExpandDepth"></a>`defaultModelsExpandDepth` | `DEFAULT_MODELS_EXPAND_DEPTH` | `Number=1`. The default expansion depth for models (set to -1 completely hide the models).
<a name="defaultModelExpandDepth"></a>`defaultModelExpandDepth` | `DEFAULT_MODEL_EXPAND_DEPTH` | `Number=1`. The default expansion depth for the model on the model-example section.
<a name="defaultModelRendering"></a>`defaultModelRendering` | `DEFAULT_MODEL_RENDERING` | `String=["example"*, "model"]`. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)
<a name="displayRequestDuration"></a>`displayRequestDuration` | `DISPLAY_REQUEST_DURATION` | `Boolean=false`. Controls the display of the request duration (in milliseconds) for Try-It-Out requests.
<a name="docExpansion"></a>`docExpansion` | `DOC_EXPANSION` | `String=["list"*, "full", "none"]`. Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing).
<a name="filter"></a>`filter` | `FILTER` | `Boolean=false OR String`. If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be Boolean to enable or disable, or a string, in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag.
<a name="maxDisplayedTags"></a>`maxDisplayedTags` | `MAX_DISPLAYED_TAGS` | `Number`. If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations.
<a name="operationsSorter"></a>`operationsSorter` | _Unavailable_ | `Function=(a => a)`. Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.
<a name="showExtensions"></a>`showExtensions` | `SHOW_EXTENSIONS` | `Boolean=false`. Controls the display of vendor extension (`x-`) fields and values for Operations, Parameters, and Schema.
<a name="showCommonExtensions"></a>`showCommonExtensions` | `SHOW_COMMON_EXTENSIONS` | `Boolean=false`. Controls the display of extensions (`pattern`, `maxLength`, `minLength`, `maximum`, `minimum`) fields and values for Parameters.
<a name="tagSorter"></a>`tagsSorter` | _Unavailable_ | `Function=(a => a)`. Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function (see [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger-UI.
<a name="onComplete"></a>`onComplete` | _Unavailable_ | `Function=NOOP`. Provides a mechanism to be notified when Swagger-UI has finished rendering a newly provided definition.
##### Network
Parameter Name | Description
--- | ---
<a name="oauth2RedirectUrl"></a>`oauth2RedirectUrl` | `String`. OAuth redirect URL.
<a name="requestInteceptor"></a>`requestInterceptor` | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 requests. Accepts one argument requestInterceptor(request) and must return the modified request, or a Promise that resolves to the modified request.
<a name="responseInterceptor"></a>`responseInterceptor` |`Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 responses. Accepts one argument responseInterceptor(response) and must return the modified response, or a Promise that resolves to the modified response.
<a name="showMutatedRequest"></a>`showMutatedRequest` | `Boolean=true`. If set to `true`, uses the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
<a name="supportedSubmitMethods"></a>`supportedSubmitMethods` | `Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]`. List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations. This does not filter the operations from the display.
<a name="validatorUrl"></a>`validatorUrl` | `String="https://online.swagger.io/validator" OR null`. By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to `null` will disable validation.
Parameter name | Docker variable | Description
--- | --- | -----
<a name="oauth2RedirectUrl"></a>`oauth2RedirectUrl` | _Unavailable_ | `String`. OAuth redirect URL.
<a name="requestInteceptor"></a>`requestInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 requests. Accepts one argument requestInterceptor(request) and must return the modified request, or a Promise that resolves to the modified request.
<a name="responseInterceptor"></a>`responseInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 responses. Accepts one argument responseInterceptor(response) and must return the modified response, or a Promise that resolves to the modified response.
<a name="showMutatedRequest"></a>`showMutatedRequest` | `SHOW_MUTATED_REQUEST` | `Boolean=true`. If set to `true`, uses the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
<a name="supportedSubmitMethods"></a>`supportedSubmitMethods` | `SUPPORTED_SUBMIT_METHODS` | `Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]`. List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations. This does not filter the operations from the display.
<a name="validatorUrl"></a>`validatorUrl` | `VALIDATOR_URL` | `String="https://online.swagger.io/validator" OR null`. By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to `null` will disable validation.
##### Macros
Parameter Name | Description
--- | ---
<a name="modelPropertyMacro"></a>`modelPropertyMacro` | `Function`. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
<a name="parameterMacro"></a>`parameterMacro` | `Function`. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
Parameter name | Docker variable | Description
--- | --- | -----
<a name="modelPropertyMacro"></a>`modelPropertyMacro` | _Unavailable_ | `Function`. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
<a name="parameterMacro"></a>`parameterMacro` | _Unavailable_ | `Function`. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
### Instance methods
Method Name | Description
--- | ---
<a name="initOAuth"></a>`initOAuth` | `(configObj) => void`. Provide Swagger-UI with information about your OAuth server - see the OAuth2 documentation for more information.
<a name="preauthorizeBasic"></a>`preauthorizeBasic` | `(authDefinitionKey, username, password) => action`. Programmatically set values for a Basic authorization scheme.
<a name="preauthorizeApiKey"></a>`preauthorizeApiKey` | `(authDefinitionKey, apiKeyValue) => action`. Programmatically set values for an API key authorization scheme.
Parameter name | Docker variable | Description
--- | --- | -----
<a name="initOAuth"></a>`initOAuth` | _Unavailable_ | `(configObj) => void`. Provide Swagger-UI with information about your OAuth server - see the OAuth2 documentation for more information.
<a name="preauthorizeBasic"></a>`preauthorizeBasic` | _Unavailable_ | `(authDefinitionKey, username, password) => action`. Programmatically set values for a Basic authorization scheme.
<a name="preauthorizeApiKey"></a>`preauthorizeApiKey` | _Unavailable_ | `(authDefinitionKey, apiKeyValue) => action`. Programmatically set values for an API key authorization scheme.
### Docker
If you're using the Docker image, you can also control most of these options with environment variables. Each parameter has its environment variable name noted, if available.
Below are the general guidelines for using the environment variable interface.
##### String variables
Set the value to whatever string you'd like, taking care to escape characters where necessary
Example:
```sh
FILTER="myFilterValue"
LAYOUT="BaseLayout"
```
##### Boolean variables
Set the value to `true` or `false`.
Example:
```sh
DISPLAY_OPERATION_ID="true"
DEEP_LINKING="false"
```
##### Number variables
Set the value to _`n`_, where _n_ is the number you'd like to provide.
Example:
```sh
DEFAULT_MODELS_EXPAND_DEPTH="5"
DEFAULT_MODEL_EXPAND_DEPTH="7"
```
##### Array variables
Set the value to the literal array value you'd like, taking care to escape characters where necessary.
Example:
```sh
SUPPORTED_SUBMIT_METHODS="[\"get\", \"post\"]"
URLS="[ { url: \"http://petstore.swagger.io/v2/swagger.json\", name: \"Petstore\" } ]"
```
##### Object variables
Set the value to the literal object value you'd like, taking care to escape characters where necessary.
Example:
```sh
SPEC="{ \"openapi\": \"3.0.0\" }"
```
......@@ -56,9 +56,9 @@ const ui = SwaggerUIBundle({
`SwaggerUIBundle` is equivalent to `SwaggerUI`.
### Docker Hub
### Docker
You can pull a pre-built docker image of the swagger-ui directly from Dockerhub:
You can pull a pre-built docker image of the swagger-ui directly from Docker Hub:
```
docker pull swaggerapi/swagger-ui
......@@ -81,6 +81,8 @@ docker run -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v
This will serve Swagger UI at `/swagger` instead of `/`.
For more information on controlling Swagger UI through the Docker image, see the Docker section of the [Configuration documentation](docs/usage/configuration.md#docker).
### unpkg
You can embed Swagger-UI's code directly in your HTML by using unpkg's interface:
......
......@@ -31,7 +31,7 @@
"lint-fix": "eslint --cache --ext '.js,.jsx' src test --fix",
"test": "run-s just-test-in-node e2e-cypress lint-errors",
"test-in-node": "run-s lint-errors just-test-in-node",
"just-test-in-node": "mocha --require test/setup.js --recursive --compilers js:babel-core/register --require source-map-support test/core test/components test/bugs test/swagger-ui-dist-package test/xss",
"just-test-in-node": "mocha --require test/setup.js --recursive --compilers js:babel-core/register --require source-map-support test/core test/components test/bugs test/docker test/swagger-ui-dist-package test/xss",
"just-check-coverage": "nyc npm run just-test-in-node",
"test-e2e-cypress": "cypress run",
"test-e2e-selenium": "sleep 3 && nightwatch test/e2e-selenium/scenarios/ --config test/e2e-selenium/nightwatch.json",
......
const expect = require("expect")
const translator = require("../../docker/configurator/translator")
const dedent = require("dedent")
describe("docker: env translator", function() {
it("should generate an empty baseline config", function() {
const input = {}
expect(translator(input)).toEqual(``)
})
it("should generate a base config including the base content", function() {
const input = {}
expect(translator(input, {
injectBaseConfig: true
})).toEqual(dedent(`
url: "https://petstore.swagger.io/v2/swagger.json",
"dom_id": "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
`))
})
it("should ignore an unknown config", function() {
const input = {
ASDF1234: "wow hello"
}
expect(translator(input)).toEqual(dedent(``))
})
it("should generate a string config", function() {
const input = {
URL: "http://petstore.swagger.io/v2/swagger.json",
FILTER: ""
}
expect(translator(input)).toEqual(dedent(`
url: "http://petstore.swagger.io/v2/swagger.json",
filter: "",`
).trim())
})
it("should generate a boolean config", function() {
const input = {
DEEP_LINKING: "true",
SHOW_EXTENSIONS: "false",
SHOW_COMMON_EXTENSIONS: ""
}
expect(translator(input)).toEqual(dedent(`
deepLinking: true,
showExtensions: false,
showCommonExtensions: undefined,`
))
})
it("should generate an object config", function() {
const input = {
SPEC: `{ swagger: "2.0" }`
}
expect(translator(input)).toEqual(dedent(`
spec: { swagger: "2.0" },`
).trim())
})
it("should generate an array config", function() {
const input = {
URLS: `["/one", "/two"]`,
SUPPORTED_SUBMIT_METHODS: ""
}
expect(translator(input)).toEqual(dedent(`
urls: ["/one", "/two"],
supportedSubmitMethods: undefined,`
).trim())
})
it("should properly escape key names when necessary", function () {
const input = {
URLS: `["/one", "/two"]`,
URLS_PRIMARY_NAME: "one",
}
expect(translator(input)).toEqual(dedent(`
urls: ["/one", "/two"],
"urls.primaryName": "one",`
).trim())
})
it("should disregard a legacy variable in favor of a regular one", function() {
const input = {
// Order is important to this test... legacy vars should be
// superseded regardless of what is fed in first.
API_URL: "/old.json",
URL: "/swagger.json",
URLS: `["/one", "/two"]`,
API_URLS: `["/three", "/four"]`,
}
expect(translator(input)).toEqual(dedent(`
url: "/swagger.json",
urls: ["/one", "/two"],`
).trim())
})
it("should generate a full config k:v string", function() {
const input = {
API_URL: "/old.yaml",
API_URLS: `["/old", "/older"]`,
CONFIG_URL: "/wow",
DOM_ID: "#swagger_ui",
SPEC: `{ swagger: "2.0" }`,
URL: "/swagger.json",
URLS: `["/one", "/two"]`,
URLS_PRIMARY_NAME: "one",
LAYOUT: "BaseLayout",
DEEP_LINKING: "false",
DISPLAY_OPERATION_ID: "true",
DEFAULT_MODELS_EXPAND_DEPTH: "0",
DEFAULT_MODEL_EXPAND_DEPTH: "1",
DEFAULT_MODEL_RENDERING: "example",
DISPLAY_REQUEST_DURATION: "true",
DOC_EXPANSION: "full",
FILTER: "wowee",
MAX_DISPLAYED_TAGS: "4",
SHOW_EXTENSIONS: "true",
SHOW_COMMON_EXTENSIONS: "false",
OAUTH2_REDIRECT_URL: "http://google.com/",
SHOW_MUTATED_REQUEST: "true",
SUPPORTED_SUBMIT_METHODS: `["get", "post"]`,
VALIDATOR_URL: "http://smartbear.com/"
}
expect(translator(input)).toEqual(dedent(`
configUrl: "/wow",
"dom_id": "#swagger_ui",
spec: { swagger: "2.0" },
url: "/swagger.json",
urls: ["/one", "/two"],
"urls.primaryName": "one",
layout: "BaseLayout",
deepLinking: false,
displayOperationId: true,
defaultModelsExpandDepth: 0,
defaultModelExpandDepth: 1,
defaultModelRendering: "example",
displayRequestDuration: true,
docExpansion: "full",
filter: "wowee",
maxDisplayedTags: 4,
showExtensions: true,
showCommonExtensions: false,
oauth2RedirectUrl: "http://google.com/",
showMutatedRequest: true,
supportedSubmitMethods: ["get", "post"],
validatorUrl: "http://smartbear.com/",`
).trim())
})
it("should generate a full config k:v string including base config", function() {
const input = {
API_URL: "/old.yaml",
API_URLS: `["/old", "/older"]`,
CONFIG_URL: "/wow",
DOM_ID: "#swagger_ui",
SPEC: `{ swagger: "2.0" }`,
URL: "/swagger.json",
URLS: `["/one", "/two"]`,
URLS_PRIMARY_NAME: "one",
LAYOUT: "BaseLayout",
DEEP_LINKING: "false",
DISPLAY_OPERATION_ID: "true",
DEFAULT_MODELS_EXPAND_DEPTH: "0",
DEFAULT_MODEL_EXPAND_DEPTH: "1",
DEFAULT_MODEL_RENDERING: "example",
DISPLAY_REQUEST_DURATION: "true",
DOC_EXPANSION: "full",
FILTER: "wowee",
MAX_DISPLAYED_TAGS: "4",
SHOW_EXTENSIONS: "true",
SHOW_COMMON_EXTENSIONS: "false",
OAUTH2_REDIRECT_URL: "http://google.com/",
SHOW_MUTATED_REQUEST: "true",
SUPPORTED_SUBMIT_METHODS: `["get", "post"]`,
VALIDATOR_URL: "http://smartbear.com/"
}
expect(translator(input, { injectBaseConfig: true })).toEqual(dedent(`
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
configUrl: "/wow",
"dom_id": "#swagger_ui",
spec: { swagger: "2.0" },
url: "/swagger.json",
urls: ["/one", "/two"],
"urls.primaryName": "one",
layout: "BaseLayout",
deepLinking: false,
displayOperationId: true,
defaultModelsExpandDepth: 0,
defaultModelExpandDepth: 1,
defaultModelRendering: "example",
displayRequestDuration: true,
docExpansion: "full",
filter: "wowee",
maxDisplayedTags: 4,
showExtensions: true,
showCommonExtensions: false,
oauth2RedirectUrl: "http://google.com/",
showMutatedRequest: true,
supportedSubmitMethods: ["get", "post"],
validatorUrl: "http://smartbear.com/",`
).trim())
})
})
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册