如何为NodeJS Serverless框架配置适配多环境的SwaggerUI
多环境适配SwaggerUI部署实现指引(NodeJS Serverless场景)
前置准备
- 已校验通过的
openapi.yml/openapi.json文档 - 项目NodeJS版本≥14.x,Serverless框架版本≥2.x
第一步:通用依赖安装
优先使用官方通用的swagger-ui-dist包实现跨环境兼容,无需绑定云厂商特定工具包,执行以下命令安装依赖:
npm install swagger-ui-dist js-yaml --save
第二步:编写多环境适配处理函数
核心逻辑是提前缓存openapi文档,动态生成SwaggerUI静态页面,同时兼容AWS Lambda APIGW事件、本地serverless-offline运行场景:
const fs = require('fs') const path = require('path') const yaml = require('js-yaml') const swaggerUiAssets = require('swagger-ui-dist') // 提前缓存openapi文档,避免每次请求重复IO操作 const openApiDoc = yaml.load(fs.readFileSync(path.join(__dirname, './openapi.yml'), 'utf8')) // 生成注入了自定义openapi文档的SwaggerUI页面 const getSwaggerHtml = () => { const rawIndex = fs.readFileSync(path.join(swaggerUiAssets.getAbsoluteFSPath(), 'index.html'), 'utf8') return rawIndex.replace( 'window.ui = SwaggerUIBundle({', `window.ui = SwaggerUIBundle({ spec: ${JSON.stringify(openApiDoc)}, dom_id: '#swagger-ui', deepLinking: true, presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset], plugins: [SwaggerUIBundle.plugins.DownloadUrl], layout: "StandaloneLayout" ` ) } // 多环境请求适配逻辑 const swaggerHandler = async (event, context) => { // 适配AWS APIGW触发场景 if (event.requestContext) { // 处理Swagger依赖的静态资源(css、js等) const assetPath = event.path.replace('/swagger', '') if (assetPath && assetPath !== '/') { const assetFullPath = path.join(swaggerUiAssets.getAbsoluteFSPath(), assetPath) if (fs.existsSync(assetFullPath)) { const content = fs.readFileSync(assetFullPath) let contentType = 'text/plain' if (assetPath.endsWith('.css')) contentType = 'text/css' if (assetPath.endsWith('.js')) contentType = 'application/javascript' return { statusCode: 200, headers: { 'Content-Type': contentType }, body: content.toString('base64'), isBase64Encoded: true } } } // 返回SwaggerUI主页面 return { statusCode: 200, headers: { 'Content-Type': 'text/html' }, body: getSwaggerHtml() } } // 适配本地serverless-offline调试场景 if (event.method === 'GET' && (event.path === '/swagger' || event.path === '/swagger/')) { return { statusCode: 200, headers: { 'Content-Type': 'text/html' }, body: getSwaggerHtml() } } // 其他云厂商Serverless环境可在此处新增事件结构判断逻辑,核心页面生成逻辑无需修改 return { statusCode: 404, body: 'Not Found' } } module.exports = { swaggerHandler }
第三步:Serverless配置更新
在serverless.yml中新增Swagger路由配置:
functions: swagger: handler: src/swagger.swaggerHandler # 替换为你实际的handler文件路径 events: - http: path: /swagger method: get cors: true - http: path: /swagger/{proxy+} method: get cors: true
验证方法
- 本地调试:启动
serverless offline后,访问http://localhost:3000/swagger即可查看UI - AWS部署:执行
serverless deploy后,访问生成的APIGW域名+/swagger路径即可访问 - 其他环境适配:仅需要在handler中新增对应云厂商的事件结构判断逻辑,不需要修改SwaggerUI生成的核心代码
注意事项
- 生产环境可在handler中新增请求鉴权逻辑,避免接口文档对外暴露
- openapi文档更新后重新部署即可同步UI内容,无需额外修改配置
- 如果需要支持openapi文件动态拉取,将代码中的静态读取逻辑替换为对应存储服务的拉取逻辑即可
内容的提问来源于stack exchange,提问作者Axel Blaz
相关产品推荐
相关产品推荐

