bug fixed

master
old易 2025-07-09 16:15:38 +08:00
parent 7e0a66a4ad
commit f7cf768dc7
1 changed files with 43 additions and 17 deletions

View File

@ -72,7 +72,6 @@ app.get('/mock-api/routes', (req, res) => {
res.json(list); res.json(list);
}); });
// ✅ Swagger 配置 // ✅ Swagger 配置
const swaggerDefinition = { const swaggerDefinition = {
openapi: '3.0.0', openapi: '3.0.0',
@ -81,31 +80,35 @@ const swaggerDefinition = {
version: '1.0.0', version: '1.0.0',
description: 'Dynamically registered mock APIs' description: 'Dynamically registered mock APIs'
}, },
servers: [{ url: `http://192.168.100.138:${PORT}`, description: 'Local server' }] servers: [] // 将由请求动态生成
}; };
function buildSwaggerSpecFromMocks(configs) { function buildSwaggerSpecFromMocks(configs) {
const paths = {}; const paths = {};
configs.forEach(({ method, path }) => { configs.forEach(({ method, path, swagger }) => {
const cleanPath = path.replace(/:([^/]+)/g, '{$1}'); const cleanPath = path.replace(/:([^/]+)/g, '{$1}');
const methodName = method.toLowerCase(); const methodName = method.toLowerCase();
paths[cleanPath] = paths[cleanPath] || {};
paths[cleanPath][methodName] = { const summary = swagger?.summary || `Mocked ${method} ${path}`;
summary: `Mocked ${method} ${path}`, const description = swagger?.description || '';
responses: { const responses = swagger?.responses || {
200: { 200: {
description: 'Mock response', description: 'Mock response',
content: { content: {
'application/json': { 'application/json': {
schema: { schema: { type: 'object' }
type: 'object'
}
}
} }
} }
} }
}; };
paths[cleanPath] = paths[cleanPath] || {};
paths[cleanPath][methodName] = {
summary,
description,
responses
};
}); });
return { return {
@ -115,9 +118,32 @@ function buildSwaggerSpecFromMocks(configs) {
} }
// ✅ Swagger UI 路由 // ✅ Swagger UI 路由
app.use('/swagger', (req, res, next) => {
res.setHeader('Cache-Control', 'no-store');
next();
});
app.use('/swagger', swaggerUi.serve, (req, res, next) => { app.use('/swagger', swaggerUi.serve, (req, res, next) => {
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.get('host');
const dynamicSwaggerDefinition = {
...swaggerDefinition,
servers: [
{
url: `${protocol}://${host}`,
description: 'Current host'
}
]
};
const spec = buildSwaggerSpecFromMocks(mockConfigs); const spec = buildSwaggerSpecFromMocks(mockConfigs);
swaggerUi.setup(spec)(req, res, next); const dynamicSpec = {
...spec,
servers: dynamicSwaggerDefinition.servers
};
swaggerUi.setup(dynamicSpec)(req, res, next);
}); });
// ✅ 启动服务 // ✅ 启动服务