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