2026-07-30 11:23:50 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 统一请求封装(基于 Nuxt 内置 ofetch)
|
2026-07-31 19:02:00 +08:00
|
|
|
|
*
|
|
|
|
|
|
* 与 dashboard 后端约定响应格式:{ code, msg, data }
|
|
|
|
|
|
* - code = 1:成功
|
|
|
|
|
|
* - code = 0:业务错误
|
|
|
|
|
|
* - code = 2:无数据
|
2026-07-30 11:23:50 +08:00
|
|
|
|
*/
|
|
|
|
|
|
|
2026-08-04 19:18:35 +08:00
|
|
|
|
import { resolveAssetUrls } from '~/utils/resolveAssetUrl';
|
|
|
|
|
|
|
2026-07-31 19:02:00 +08:00
|
|
|
|
export interface ApiResponse<T = unknown> {
|
|
|
|
|
|
code: number;
|
|
|
|
|
|
msg: string;
|
|
|
|
|
|
data: T | null;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export class ApiError extends Error {
|
|
|
|
|
|
code: number;
|
|
|
|
|
|
constructor(msg: string, code: number) {
|
|
|
|
|
|
super(msg);
|
|
|
|
|
|
this.code = code;
|
|
|
|
|
|
}
|
2026-07-30 11:23:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export function useRequest() {
|
|
|
|
|
|
const config = useRuntimeConfig();
|
|
|
|
|
|
const baseURL = config.public.apiBaseUrl as string;
|
|
|
|
|
|
|
2026-07-31 19:02:00 +08:00
|
|
|
|
async function request<T = unknown>(url: string, options?: Parameters<typeof $fetch>[1]): Promise<T | null> {
|
2026-07-30 11:23:50 +08:00
|
|
|
|
const res = await $fetch<ApiResponse<T>>(url, {
|
|
|
|
|
|
baseURL,
|
|
|
|
|
|
...options
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-07-31 19:02:00 +08:00
|
|
|
|
if (res.code === 0) {
|
|
|
|
|
|
throw new ApiError(res.msg || '请求失败', res.code);
|
2026-07-30 11:23:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-31 19:02:00 +08:00
|
|
|
|
// code = 2(无数据)时 data 为 null,正常返回
|
2026-08-04 19:18:35 +08:00
|
|
|
|
// 统一解析 *_url / *_path 字段中的相对路径(如 /uploads/...)为完整资源地址
|
|
|
|
|
|
return resolveAssetUrls(res.data);
|
2026-07-30 11:23:50 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function get<T = unknown>(url: string, params?: Record<string, unknown>) {
|
|
|
|
|
|
return request<T>(url, { method: 'GET', params });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function post<T = unknown>(url: string, body?: Record<string, unknown>) {
|
|
|
|
|
|
return request<T>(url, { method: 'POST', body });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-20 16:42:01 +08:00
|
|
|
|
/** POST multipart/form-data(文件上传;ofetch 自动设置 boundary) */
|
|
|
|
|
|
function postForm<T = unknown>(url: string, body: FormData) {
|
|
|
|
|
|
return request<T>(url, { method: 'POST', body });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return { request, get, post, postForm };
|
2026-07-30 11:23:50 +08:00
|
|
|
|
}
|