You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.4 KiB
JavaScript

const express = require('express'); //引入express
const Mock = require('mockjs'); //引入mock
const fs = require('fs');
const app = express(); //实例化express
const {
routerLog,
writeLog
} = require('./writeLog');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
fs.writeFile('./routerLog.md', ' \n # 路由 \n', function(error) {
if (error) {
console.log('写入失败')
} else {
console.log('markdown 写入路由记录')
}
})
const directory = './data/';
loopPath(directory);
//循环目录
function loopPath(directory) {
const paths = fs.readdirSync(directory);
let logs = "";
for (let i = 0; i < paths.length; i++) {
const file = directory + paths[i];
if (isDirectory(file)) {
const subDirectory = file + "/";
loopPath(subDirectory);
} else {
if (fs.existsSync(`${file}`)) {
const dataConfigs = require(`${file}`);
// console.log('dataConfigs', dataConfigs);
const configs = dataConfigs.routerConfigs;
const baseUrl = dataConfigs.basicRouteUrl;
logs += `\n ## 路由 --- ${dataConfigs.basicRouteName} \n\n`;
for (let i = 0; i < configs.length; i++) {
configs[i].responseExample = JSON.stringify(
FormatMockData({
data: configs[i].mockData
})
);
logs += routerLog(configs[i]);
const { url, type } = configs[i];
const mockUrl = "/" + baseUrl + url;
console.log("路由信息:", "url:", mockUrl, "type:", type);
loopRouteConfig(mockUrl, configs[i]);
}
}
}
}
writeLog(logs);
}
// 注册路由
function loopRouteConfig(mockUrl, { type, mockData }) {
app[type](mockUrl, function(req, res) {
res.json(
FormatMockData({
mockData
})
);
});
}
// 是否为目录
function isDirectory(directory) {
return fs.lstatSync(directory).isDirectory() ? true : false;
}
// mock 模拟数据 mock json
function FormatMockData({ mockData }) {
const status200 = { code: 0, message: "成功" };
return {
...status200,
...Mock.mock(mockData)
};
}
app.listen('8090', () => {
console.log('mock 模拟地址 http://localhost:8090/')
})