| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import {getRoleRoute} from "@/api/system/role.js";
- /**
- * 角色路由缓存配置
- */
- const CONFIG = {
- USER_ROLE_ROUTE_KEY: 'user_role_route',
- USER_ROLE_ROUTE_MENU_KEY: 'user_role_route_menu',
- EXPIRY_SUFFIX: '_expiry',
- EXPIRY_TIME: 24 * 60 * 60 * 1000 // 24小时
- }
- const ROLE_KEY = {
- COURSE: 'course',
- BLOCKLY: 'blockly',
- AI_COURSE: 'aiCourse',
- AI_POETRY: 'aiPoetry'
- }
- /**
- * 刷新角色路由缓存
- * @returns {Promise<Array>} - 角色路由数组
- */
- export const refreshRoleRoute = async () => {
- try {
- // 缓存不存在或已过期,从服务器获取
- const res = await getRoleRoute();
- if (res.code === 0) {
- // 存储到localStorage并设置过期时间
- setCacheWithExpiry(CONFIG.USER_ROLE_ROUTE_KEY, res.data.routeList);
- setCacheWithExpiry(CONFIG.USER_ROLE_ROUTE_MENU_KEY, res.data.courseRouteMenuList);
- return res.data.routeList;
- } else {
- console.error(`获取角色路由数据失败:`, res.msg);
- return [];
- }
- } catch (error) {
- console.error(`获取角色路由数据失败:`, error);
- return [];
- }
- };
- /**
- * 检查缓存是否过期
- * @param {string} key - 缓存键
- * @returns {boolean} - 是否已过期
- */
- const isCacheExpired = (key) => {
- const expiryKey = `${key}${CONFIG.EXPIRY_SUFFIX}`;
- const expiryTime = localStorage.getItem(expiryKey);
- if (!expiryTime) return true;
- return Date.now() > parseInt(expiryTime);
- };
- /**
- * 设置带过期时间的缓存
- * @param {string} key - 缓存键
- * @param {any} data - 要缓存的数据
- */
- const setCacheWithExpiry = (key, data) => {
- localStorage.setItem(key, JSON.stringify(data));
- // 设置过期时间
- const expiryKey = `${key}${CONFIG.EXPIRY_SUFFIX}`;
- const expiryTime = Date.now() + CONFIG.EXPIRY_TIME;
- localStorage.setItem(expiryKey, expiryTime.toString());
- };
- /**
- * 取指定key的缓存
- * @returns {any} - 缓存数据
- */
- const getRoleRouteCache = () => {
- // 检查缓存是否存在且未过期
- const cachedData = localStorage.getItem(CONFIG.USER_ROLE_ROUTE_KEY);
- if (cachedData && !isCacheExpired(CONFIG.USER_ROLE_ROUTE_KEY)) {
- return JSON.parse(cachedData);
- }
- return refreshRoleRoute();
- }
- export { CONFIG,ROLE_KEY,setCacheWithExpiry,getRoleRouteCache };
|