Files
front-pc/composables/useDollarFetchRequest.ts
2025-08-24 21:06:11 +08:00

76 lines
2.1 KiB
TypeScript

import { isArray } from "~/utils/utils";
import refreshToken from "~/utils/RefreshToken";
type FetchType = typeof $fetch;
export type FetchOptions = Parameters<FetchType>[1];
const useClientRequest = async <T = unknown>(
url: string,
opts?: FetchOptions
) => {
// const token = useCookie<string | undefined>("token");
const runtimeConfig = useRuntimeConfig();
const defaultOptions: FetchOptions = {
baseURL: runtimeConfig.public.apiBase,
onRequest({ options }) {
options.headers = options.headers || 'application/json';
if (refreshToken.getToken().token) {
options.headers.set("Authorization", `Bearer ${refreshToken.getToken().token}`);
}
},
onResponse({ response }) {
if (+response.status === 200 && +response._data.code !== 0) {
ElMessage.error(response._data.msg);
}
},
onResponseError({ response }) {
ElMessage.error(
isArray(response._data.data.msg)
? response._data.data.msg[0]
: response._data.data.msg
);
},
};
// 明确转换返回类型
const response = await $fetch(url, { ...defaultOptions, ...opts });
return response as unknown as T;
};
// GET请求
export const get = <T = unknown>(
endpoint: string,
config?: Omit<FetchOptions, 'method'>
): Promise<T> => {
return useClientRequest<T>(endpoint, { ...config, method: 'GET' })
}
// POST请求
export const post = <T = unknown>(
endpoint: string,
body?: any,
config?: Omit<FetchOptions, 'method' | 'body'>
): Promise<T> => {
return useClientRequest<T>(endpoint, { ...config, method: 'POST', body })
}
// DELETE请求
export const del = <T = unknown>(
endpoint: string,
config?: Omit<FetchOptions, 'method'>
): Promise<T> => {
return useClientRequest<T>(endpoint, { ...config, method: 'DELETE' })
}
// PUT请求
export const put = <T = unknown>(
endpoint: string,
body?: any,
config?: Omit<FetchOptions, 'method' | 'body'>
): Promise<T> => {
return useClientRequest<T>(endpoint, { ...config, method: 'PUT', body })
}