你可以用wrapComponents
样本openapi.yaml
openapi: 3.0.1
info:
title: Swagger Petstore
description: 'This is a sample server Petstore server'
version: 1.0.0
servers:
- url: https://petstore.swagger.io/v2
- url: http://petstore.swagger.io/v2
paths:
/router/rest:
get:
summary: test
operationId: test
responses:
'200':
content:
application/json:
schema:
type: object
examples:
success:
summary: JSON example
value: Loading...
externalValue: 'example/test.json'
application/xml:
schema:
type: object
xml:
name: xml
examples:
success:
summary: XML example
value: Loading...
externalValue: 'example/test.xml'
添加自定义插件到index.html
// Examples map
const examples = {};
// Custom plugin for the logic that happens before the response element is created
const CustomPlugin = () => {
return {
wrapComponents: {
response: (Original, { React, oas3Actions, oas3Selectors }) => (props) => {
const contentType = oas3Selectors.responseContentType(props.path, props.method)
const externalValue = props.response.getIn(['content', contentType, 'examples', props.activeExamplesKey, 'externalValue'])
// Check if externalValue field exists
if (externalValue) {
// Check if examples map already contains externalValue key
if (examples[externalValue]) {
// Set example value directly from examples map
props.response = props.response.setIn(['content', contentType, 'examples', props.activeExamplesKey, 'value'], examples[externalValue])
} else {
// Download external file
fetch(externalValue)
.then(res => res.text())
.then(data => {
// Put downloaded file content into the examples map
examples[externalValue] = data
// Simulate select another example action
oas3Actions.setActiveExamplesMember({
"name": 'fake',
"pathMethod": [props.path, props.method],
"contextType": "responses",
"contextName": props.code
})
// Reselect this example
oas3Actions.setActiveExamplesMember({
"name": props.activeExamplesKey,
"pathMethod": [props.path, props.method],
"contextType": "responses",
"contextName": props.code
})
})
.catch(e => console.error(e))
}
}
return React.createElement(Original, props)
}
}
}
}
window.onload = function() {
const ui = SwaggerUIBundle({
url: 'openapi.yaml',
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
// Add custom plugin
CustomPlugin
],
layout: "StandaloneLayout"
});
window.ui = ui;
};