feat: 重构前端api封装结构

This commit is contained in:
2025-12-16 22:51:27 +08:00
parent 0018b50914
commit 5ce34c4c95
46 changed files with 211 additions and 441 deletions

View File

@@ -1,34 +1,48 @@
// import { headers } from 'next/headers'
import { APIResponse, HttpMethod, normalizeAPIError } from './common';
export async function apiFetch<T extends unknown>(
url: string,
options: RequestInit = {}
interface ClientFetchRequestOptions extends RequestInit {
method?: HttpMethod;
body?: any;
}
export async function clientFetch<T = unknown>(
endpoint: string,
options: ClientFetchRequestOptions = {}
): Promise<T> {
// const nextHeaders = await headers()
const defaultHeaders: HeadersInit = {
'Content-Type': 'application/json',
// ...nextHeaders,
}
};
try {
const res = await fetch(new URL(url, process.env.API_BASE), {
...options,
const response = await fetch(endpoint, {
method: options.method || 'GET',
headers: {
...defaultHeaders,
...options.headers,
},
cache: 'no-store',
body: options.body ?? JSON.stringify(options.body),
credentials: 'include',
...options,
});
if (res.status === 200) {
const data = await res.json();
if (data.statusCode === 200) {
return data.data;
}
throw new Error(data.message ?? '未知错误');
if (!response.ok) {
const errorText = await response.text();
throw JSON.parse(errorText);
}
throw new Error('请求失败');
const data: APIResponse<T> = await response.json();
if (!data.success) {
throw data;
}
return data.data as T;
} catch (error) {
throw error;
normalizeAPIError(error);
}
}
}
export * as AuthAPI from './endpoints/auth.client'