refactor(storage): ♻️ 简化缓存管理方式,统一使用Storage类直接操作token和缓存

This commit is contained in:
Ray.Hao
2025-05-19 14:09:46 +08:00
parent a6d76d17d8
commit 2a3d2543ee
10 changed files with 71 additions and 47 deletions

View File

@@ -1,27 +0,0 @@
// 访问 token 缓存的 key
const ACCESS_TOKEN_KEY = "access_token";
// 刷新 token 缓存的 key
const REFRESH_TOKEN_KEY = "refresh_token";
function getAccessToken(): string {
return localStorage.getItem(ACCESS_TOKEN_KEY) || "";
}
function setAccessToken(token: string) {
localStorage.setItem(ACCESS_TOKEN_KEY, token);
}
function getRefreshToken(): string {
return localStorage.getItem(REFRESH_TOKEN_KEY) || "";
}
function setRefreshToken(token: string) {
localStorage.setItem(REFRESH_TOKEN_KEY, token);
}
function clearToken() {
localStorage.removeItem(ACCESS_TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
}
export { getAccessToken, setAccessToken, clearToken, getRefreshToken, setRefreshToken };

View File

@@ -2,7 +2,8 @@ import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axio
import qs from "qs";
import { useUserStoreHook } from "@/store/modules/user.store";
import { ResultEnum } from "@/enums/api/result.enum";
import { getAccessToken } from "@/utils/auth";
import { Storage } from "@/utils/storage";
import { ACCESS_TOKEN_KEY } from "@/constants/cache-keys";
import router from "@/router";
// 创建 axios 实例
@@ -15,7 +16,7 @@ const service = axios.create({
// 请求拦截器
service.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const accessToken = getAccessToken();
const accessToken = Storage.get(ACCESS_TOKEN_KEY, "");
// 如果 Authorization 设置为 no-auth则不携带 Token
if (config.headers.Authorization !== "no-auth" && accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
@@ -69,7 +70,7 @@ async function handleTokenRefresh(config: InternalAxiosRequestConfig) {
return new Promise((resolve) => {
// 封装需要重试的请求
const retryRequest = () => {
config.headers.Authorization = `Bearer ${getAccessToken()}`;
config.headers.Authorization = `Bearer ${Storage.get(ACCESS_TOKEN_KEY, "")}`;
resolve(service(config));
};
waitingQueue.push(retryRequest);

37
src/utils/storage.ts Normal file
View File

@@ -0,0 +1,37 @@
/**
* 存储工具类
* 提供localStorage和sessionStorage操作方法
*/
export class Storage {
/**
* localStorage 存储
*/
static set(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
}
static get<T>(key: string, defaultValue?: T): T {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : defaultValue;
}
static remove(key: string): void {
localStorage.removeItem(key);
}
/**
* sessionStorage 存储
*/
static sessionSet(key: string, value: any): void {
sessionStorage.setItem(key, JSON.stringify(value));
}
static sessionGet<T>(key: string, defaultValue?: T): T {
const value = sessionStorage.getItem(key);
return value ? JSON.parse(value) : defaultValue;
}
static sessionRemove(key: string): void {
sessionStorage.removeItem(key);
}
}