refactor: ♻️ 优化请求工具类

This commit is contained in:
ray
2024-10-13 11:18:19 +08:00
parent a7757213f2
commit 3dec53af38
6 changed files with 90 additions and 46 deletions

View File

@@ -1,6 +1,7 @@
import { defineStore } from "pinia";
import AuthAPI from "@/api/auth";
import UserAPI, { UserInfo } from "@/api/user";
import { setToken, clearToken } from "@/utils/auth";
export const useUserStore = defineStore("user", () => {
// 确保 token 是响应式的
@@ -8,10 +9,22 @@ export const useUserStore = defineStore("user", () => {
const userInfo = ref<UserInfo | null>(null);
// 登录
const login = async (username: string, password: string) => {
const { tokenType, accessToken } = await AuthAPI.login(username, password);
token.value = `${tokenType} ${accessToken}`; // Bearer token
uni.setStorageSync("token", token.value);
const login = (username: string, password: string) => {
AuthAPI.login(username, password)
.then((res) => {
token.value = ` ${res.accessToken}`; // Bearer token
setToken(token.value);
})
.catch((error) => {
if (error.action === "TOKEN_INVALID") {
// 处理 Token 失效,比如弹出登录提示框,而不是直接跳转
console.log("Token 已失效,请重新登录");
// 例如uni.navigateTo({ url: '/pages/login/index' });
} else {
// 处理其他错误
console.error("请求失败", error.message);
}
});
};
// 获取用户信息
@@ -25,7 +38,7 @@ export const useUserStore = defineStore("user", () => {
await AuthAPI.logout();
userInfo.value = null;
token.value = ""; // 清空 token
uni.removeStorageSync("token"); // 从本地缓存移除 token
clearToken(); // 从本地缓存移除 token
};
return {