storage.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Cookies from 'js-cookie';
  2. /**
  3. * window.localStorage 浏览器永久缓存
  4. * @method set 设置永久缓存
  5. * @method get 获取永久缓存
  6. * @method remove 移除永久缓存
  7. * @method clear 移除全部永久缓存
  8. */
  9. export const Local = {
  10. // 查看 v2.4.3版本更新日志
  11. setKey(key: string) {
  12. // @ts-ignore
  13. return `${__NEXT_NAME__}:${key}`;
  14. },
  15. // 设置永久缓存
  16. set<T>(key: string, val: T) {
  17. window.localStorage.setItem(Local.setKey(key), JSON.stringify(val));
  18. },
  19. // 获取永久缓存
  20. get(key: string) {
  21. let json = <string>window.localStorage.getItem(Local.setKey(key));
  22. return JSON.parse(json);
  23. },
  24. // 移除永久缓存
  25. remove(key: string) {
  26. window.localStorage.removeItem(Local.setKey(key));
  27. },
  28. // 移除全部永久缓存
  29. clear() {
  30. window.localStorage.clear();
  31. },
  32. };
  33. /**
  34. * window.sessionStorage 浏览器临时缓存
  35. * @method set 设置临时缓存
  36. * @method get 获取临时缓存
  37. * @method remove 移除临时缓存
  38. * @method clear 移除全部临时缓存
  39. */
  40. export const Session = {
  41. // 设置临时缓存
  42. set(key: string, val: any) {
  43. if (key === 'token' || key === 'refresh_token') {
  44. Cookies.set(key, val);
  45. }
  46. window.sessionStorage.setItem(key, JSON.stringify(val));
  47. },
  48. // 获取临时缓存
  49. get(key: string) {
  50. if (key === 'token' || key === 'refresh_token') return Cookies.get(key);
  51. let json = <string>window.sessionStorage.getItem(key);
  52. return JSON.parse(json);
  53. },
  54. // 移除临时缓存
  55. remove(key: string) {
  56. if (key === 'token' || key === 'refresh_token') return Cookies.remove(key);
  57. window.sessionStorage.removeItem(key);
  58. },
  59. // 移除全部临时缓存
  60. clear() {
  61. Cookies.remove('token');
  62. Cookies.remove('refresh_token');
  63. Cookies.remove('tenantId');
  64. window.sessionStorage.clear();
  65. },
  66. // 获取当前存储的 token
  67. getToken() {
  68. return this.get('token');
  69. },
  70. // 获取当前的租户
  71. getTenant() {
  72. return Local.get('tenantId') ? Local.get('tenantId') : 1;
  73. },
  74. };