78 lines
2.3 KiB
JavaScript
78 lines
2.3 KiB
JavaScript
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
class MenuDataService {
|
||
constructor() {
|
||
// 从环境变量获取路径配置
|
||
this.dataDir = process.env.TEST_DATA_DIR || path.join(process.cwd(), 'test-data');
|
||
this.menuDataPath = process.env.MENU_DATA_FILE_PATH || path.join(this.dataDir, 'menu-data.json');
|
||
this.progressPath = process.env.TEST_PROGRESS_FILE_PATH || path.join(this.dataDir, 'test-progress.json');
|
||
|
||
// 确保数据目录存在
|
||
if (!fs.existsSync(this.dataDir)) {
|
||
fs.mkdirSync(this.dataDir, { recursive: true });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 保存菜单数据
|
||
* @param {Array} menuItems - 从页面获取的原始菜单项
|
||
* @returns {Array} - 处理后的菜单数据
|
||
*/
|
||
saveMenuData(menuItems) {
|
||
const menuData = menuItems.map((menu, index) => ({
|
||
id: index + 1,
|
||
text: menu.text,
|
||
path: menu.path || menu.text,
|
||
hasThirdMenu: menu.hasThirdMenu,
|
||
parentMenu: menu.parentMenu
|
||
}));
|
||
fs.writeFileSync(this.menuDataPath, JSON.stringify(menuData, null, 2));
|
||
return menuData;
|
||
}
|
||
|
||
/**
|
||
* 读取菜单数据
|
||
* @returns {Array|null} - 菜单数据数组,如果文件不存在则返回null
|
||
*/
|
||
getMenuData() {
|
||
if (!fs.existsSync(this.menuDataPath)) {
|
||
return null;
|
||
}
|
||
return JSON.parse(fs.readFileSync(this.menuDataPath, 'utf8'));
|
||
}
|
||
|
||
/**
|
||
* 保存测试进度
|
||
* @param {Array} completedMenus - 已完成测试的菜单ID数组
|
||
*/
|
||
saveProgress(completedMenus) {
|
||
fs.writeFileSync(this.progressPath, JSON.stringify(completedMenus, null, 2));
|
||
}
|
||
|
||
/**
|
||
* 读取测试进度
|
||
* @returns {Array} - 已完成测试的菜单ID数组
|
||
*/
|
||
getProgress() {
|
||
if (!fs.existsSync(this.progressPath)) {
|
||
return [];
|
||
}
|
||
return JSON.parse(fs.readFileSync(this.progressPath, 'utf8'));
|
||
}
|
||
|
||
/**
|
||
* 清理所有数据文件
|
||
*/
|
||
clearAll() {
|
||
if (fs.existsSync(this.menuDataPath)) {
|
||
fs.unlinkSync(this.menuDataPath);
|
||
}
|
||
if (fs.existsSync(this.progressPath)) {
|
||
fs.unlinkSync(this.progressPath);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 导出单例实例
|
||
module.exports = new MenuDataService();
|