我正在尝试找到一个解决方案,以通过单个Express应用程序拥有多个swaggerUi文档。
我正在使用 :
"typescript": "^2.5.2",
"swagger-tools": "^0.10.1",
"express": "^4.15.3",
"express-openapi": "^1.0.1",
我的 Swagger 的doc文件部分是由项目文件体系结构生成的。
我怎样才能做到这一点 ?
编辑 - -
现在,我正在像这样初始化swaggerUi:
const openapi = Openapi.initialize({
paths: openApiPaths,
expressApp,
swaggerApiDoc,
});
const openApiSpec: any = openapi.apiDoc;
app.use(swaggerUI(openApiSpec));
其中
openApiPaths
包含swagger文档的paths:{}
最佳答案
迟了一年,但仍然有效:
async function initialize (app) {
const authenticationSpec = path.join(__dirname,'api/authentication.yaml');
const authenticationMiddleware = await useSwaggerMiddlewares(authenticationSpec, {
router: routerOptions,
validator: validatorOptions,
});
// NOTE the metadata must be mounted at root level!
app.use(authenticationMiddleware.metadata);
app.use('/v2/authentication', authenticationMiddleware.validator);
app.use('/v2/authentication', authenticationMiddleware.router);
app.use('/v2/authentication', authenticationMiddleware.ui);
const mainSpec = path.join(__dirname,'api/swagger.yaml');
const mainMiddleware = await useSwaggerMiddlewares(mainSpec, {
router: routerOptions,
validator: validatorOptions,
});
app.use(mainMiddleware.metadata);
app.use(mainMiddleware.validator);
app.use(mainMiddleware.router);
app.use(mainMiddleware.ui);
// Start the server
http.createServer(app).listen(serverPort, () => console.log(`server lintening on port ${serverPort}`);
}
initialize(app);
使用在这里定义的useSwaggerMiddlewares
module.exports = function useSwaggerMiddlewares (swaggerSpec, {
router: routerOptions, validator: validatorOptions,
}) {
return new Promise((resolve, reject) => {
try {
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
const spec = fs.readFileSync(swaggerSpec, 'utf8');
const swaggerDoc = jsyaml.safeLoad(spec);
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, (middleware) => {
try {
return resolve({
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
metadata: middleware.swaggerMetadata(),
// Validate Swagger requests
validator: middleware.swaggerValidator(validatorOptions),
// Route validated requests to appropriate controller
router: middleware.swaggerRouter(routerOptions),
// Serve the Swagger documents and Swagger UI
ui: middleware.swaggerUi()
});
} catch (error) {
console.error(error);
return reject(error);
}
});
} catch (error) {
console.error(error);
return reject(error);
}
});
};
关于node.js - 带有单个Express应用程序的多个swaggerUi,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48339325/