roleUtils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import {getRoleRoute} from "@/api/system/role.js";
  2. /**
  3. * 角色路由缓存配置
  4. */
  5. const CONFIG = {
  6. USER_ROLE_ROUTE_KEY: 'user_role_route',
  7. USER_ROLE_ROUTE_MENU_KEY: 'user_role_route_menu',
  8. EXPIRY_SUFFIX: '_expiry',
  9. EXPIRY_TIME: 24 * 60 * 60 * 1000 // 24小时
  10. }
  11. const ROLE_KEY = {
  12. COURSE: 'course',
  13. BLOCKLY: 'blockly',
  14. AI_COURSE: 'aiCourse',
  15. AI_POETRY: 'aiPoetry'
  16. }
  17. /**
  18. * 刷新角色路由缓存
  19. * @returns {Promise<Array>} - 角色路由数组
  20. */
  21. export const refreshRoleRoute = async () => {
  22. try {
  23. // 缓存不存在或已过期,从服务器获取
  24. const res = await getRoleRoute();
  25. if (res.code === 0) {
  26. // 存储到localStorage并设置过期时间
  27. setCacheWithExpiry(CONFIG.USER_ROLE_ROUTE_KEY, res.data.routeList);
  28. setCacheWithExpiry(CONFIG.USER_ROLE_ROUTE_MENU_KEY, res.data.courseRouteMenuList);
  29. return res.data.routeList;
  30. } else {
  31. console.error(`获取角色路由数据失败:`, res.msg);
  32. return [];
  33. }
  34. } catch (error) {
  35. console.error(`获取角色路由数据失败:`, error);
  36. return [];
  37. }
  38. };
  39. /**
  40. * 检查缓存是否过期
  41. * @param {string} key - 缓存键
  42. * @returns {boolean} - 是否已过期
  43. */
  44. const isCacheExpired = (key) => {
  45. const expiryKey = `${key}${CONFIG.EXPIRY_SUFFIX}`;
  46. const expiryTime = localStorage.getItem(expiryKey);
  47. if (!expiryTime) return true;
  48. return Date.now() > parseInt(expiryTime);
  49. };
  50. /**
  51. * 设置带过期时间的缓存
  52. * @param {string} key - 缓存键
  53. * @param {any} data - 要缓存的数据
  54. */
  55. const setCacheWithExpiry = (key, data) => {
  56. localStorage.setItem(key, JSON.stringify(data));
  57. // 设置过期时间
  58. const expiryKey = `${key}${CONFIG.EXPIRY_SUFFIX}`;
  59. const expiryTime = Date.now() + CONFIG.EXPIRY_TIME;
  60. localStorage.setItem(expiryKey, expiryTime.toString());
  61. };
  62. /**
  63. * 取指定key的缓存
  64. * @returns {any} - 缓存数据
  65. */
  66. const getRoleRouteCache = () => {
  67. // 检查缓存是否存在且未过期
  68. const cachedData = localStorage.getItem(CONFIG.USER_ROLE_ROUTE_KEY);
  69. if (cachedData && !isCacheExpired(CONFIG.USER_ROLE_ROUTE_KEY)) {
  70. return JSON.parse(cachedData);
  71. }
  72. return refreshRoleRoute();
  73. }
  74. export { CONFIG,ROLE_KEY,setCacheWithExpiry,getRoleRouteCache };