bug fixed
parent
7e0a66a4ad
commit
f7cf768dc7
58
server.js
58
server.js
|
|
@ -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: {
|
||||
200: {
|
||||
description: 'Mock response',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object'
|
||||
}
|
||||
}
|
||||
|
||||
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' }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
// ✅ 启动服务
|
||||
|
|
|
|||
Loading…
Reference in New Issue