68 lines
1.7 KiB
JavaScript
68 lines
1.7 KiB
JavaScript
const express = require('express');
|
|
const bodyParser = require('body-parser');
|
|
const Mock = require('mockjs');
|
|
const fs = require('fs-extra');
|
|
const dayjs = require('dayjs');
|
|
const app = express();
|
|
const PORT = 3000;
|
|
const CONFIG_PATH = './mock-config.json';
|
|
|
|
app.use(bodyParser.json());
|
|
|
|
// 加载已有配置
|
|
let mockConfigs = fs.existsSync(CONFIG_PATH) ? fs.readJsonSync(CONFIG_PATH) : [];
|
|
|
|
// 标准响应结构封装
|
|
function formatResponse(data, status = 200, message = 'success') {
|
|
return {
|
|
code: status,
|
|
type: status === 200 ? 'success' : 'error',
|
|
message,
|
|
result: data,
|
|
extras: null,
|
|
time: dayjs().format('YYYY-MM-DD HH:mm:ss')
|
|
};
|
|
}
|
|
|
|
// 注册 mock 接口
|
|
function registerMockApi(config) {
|
|
const { method, path, response } = config;
|
|
const lowerMethod = method.toLowerCase();
|
|
|
|
app[lowerMethod](path, (req, res) => {
|
|
try {
|
|
const mockData = Mock.mock(response);
|
|
res.json(formatResponse(mockData));
|
|
} catch (err) {
|
|
res.json(formatResponse(null, 500, err.message));
|
|
}
|
|
});
|
|
}
|
|
|
|
// 初始化注册
|
|
mockConfigs.forEach(registerMockApi);
|
|
|
|
// 添加新 mock 接口
|
|
app.post('/mock-api/add', async (req, res) => {
|
|
const config = req.body;
|
|
if (!config.method || !config.path || !config.response) {
|
|
return res.json(formatResponse(null, 400, '参数不完整'));
|
|
}
|
|
|
|
registerMockApi(config);
|
|
mockConfigs.push(config);
|
|
await fs.writeJson(CONFIG_PATH, mockConfigs, { spaces: 2 });
|
|
|
|
res.json(formatResponse({ path: config.path }, 200, '接口已添加'));
|
|
});
|
|
|
|
// 获取所有 mock 接口
|
|
app.get('/mock-api/list', (req, res) => {
|
|
res.json(formatResponse(mockConfigs));
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`✅ Mock server is running at http://localhost:${PORT}`);
|
|
});
|
|
|