61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
import {
|
|
userInfoRespSchema,
|
|
userInfoRespSchemaNullable,
|
|
type SucceedUserInfoResp,
|
|
type SucceedUserInfoRespNullable,
|
|
} from '@/schemas/response';
|
|
import { useUserStore } from '@/stores/user';
|
|
import axios, { type AxiosError } from 'axios';
|
|
import { ElMessage } from 'element-plus';
|
|
import { errorMessage } from '../utils/api';
|
|
|
|
const baseURL = 'https://wzpmc.cn:18080/';
|
|
const axiosInstance = axios.create({
|
|
baseURL,
|
|
});
|
|
// 自动添加token到请求中.
|
|
axiosInstance.interceptors.request.use((config) => {
|
|
const userStore = useUserStore();
|
|
config.headers.setAuthorization(userStore.token, false);
|
|
return config;
|
|
});
|
|
// 自动获取响应中的token.
|
|
axiosInstance.interceptors.response.use((response) => {
|
|
const userStore = useUserStore();
|
|
const authorization = response.headers['set-authorization'] as string | undefined;
|
|
if (authorization) {
|
|
console.log(123);
|
|
userStore.token = authorization;
|
|
}
|
|
return response;
|
|
});
|
|
export default axiosInstance;
|
|
export type RawResp = Record<string, unknown>;
|
|
export async function getUserInfo(showErrorMessage: boolean): Promise<SucceedUserInfoResp>;
|
|
export async function getUserInfo(
|
|
showErrorMessage: boolean,
|
|
userID: number,
|
|
): Promise<SucceedUserInfoRespNullable>;
|
|
export async function getUserInfo(showErrorMessage: boolean, userID?: number) {
|
|
let url = '/api/user/info';
|
|
if (userID !== undefined) {
|
|
url += `/${userID}`;
|
|
}
|
|
const raw = await axiosInstance
|
|
.get<RawResp>(url)
|
|
.then((r) => r.data)
|
|
.catch((e: AxiosError) => {
|
|
if (!showErrorMessage) return;
|
|
ElMessage.error(errorMessage('获取用户信息失败', e.code, e.message));
|
|
});
|
|
if (!raw) return;
|
|
const resp = (userID !== undefined ? userInfoRespSchemaNullable : userInfoRespSchema).parse(raw);
|
|
if (resp.type === 'error') {
|
|
if (showErrorMessage) {
|
|
ElMessage.error(errorMessage('获取用户信息失败', resp.code, resp.msg));
|
|
}
|
|
return;
|
|
}
|
|
return resp;
|
|
}
|