79 lines
2.5 KiB
TypeScript
79 lines
2.5 KiB
TypeScript
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
|
|
|
|
async function fetchWithAuth(
|
|
url: string,
|
|
options: RequestInit = {},
|
|
token?: string
|
|
) {
|
|
const headers: Record<string, string> = {
|
|
"Content-Type": "application/json",
|
|
...((options.headers as Record<string, string>) || {}),
|
|
};
|
|
if (token) {
|
|
headers["Authorization"] = `Bearer ${token}`;
|
|
}
|
|
const res = await fetch(`${API_BASE}${url}`, { ...options, headers });
|
|
|
|
if (res.status === 401) {
|
|
if (typeof window !== "undefined") {
|
|
window.location.href = "/login";
|
|
}
|
|
throw new Error("登录已过期,请重新登录");
|
|
}
|
|
|
|
if (!res.ok) {
|
|
let errorDetail = `请求失败 (HTTP ${res.status})`;
|
|
try {
|
|
const error = await res.json();
|
|
errorDetail = error.detail || error.message || errorDetail;
|
|
} catch {
|
|
// 解析失败,使用默认错误信息
|
|
}
|
|
throw new Error(errorDetail);
|
|
}
|
|
|
|
if (res.status === 204) {
|
|
return null;
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
export const api = {
|
|
auth: {
|
|
register: (data: { name: string; email: string; password: string }) =>
|
|
fetchWithAuth("/api/v1/auth/register", {
|
|
method: "POST",
|
|
body: JSON.stringify(data),
|
|
}),
|
|
login: (data: { email: string; password: string }) =>
|
|
fetchWithAuth("/api/v1/auth/login", {
|
|
method: "POST",
|
|
body: JSON.stringify(data),
|
|
}),
|
|
getMe: (token: string) => fetchWithAuth("/api/v1/auth/me", {}, token),
|
|
},
|
|
queries: {
|
|
list: (token: string) => fetchWithAuth("/api/v1/queries/", {}, token),
|
|
create: (token: string, data: unknown) =>
|
|
fetchWithAuth("/api/v1/queries/", { method: "POST", body: JSON.stringify(data) }, token),
|
|
update: (token: string, id: string, data: unknown) =>
|
|
fetchWithAuth(`/api/v1/queries/${id}`, { method: "PUT", body: JSON.stringify(data) }, token),
|
|
delete: (token: string, id: string) =>
|
|
fetchWithAuth(`/api/v1/queries/${id}`, { method: "DELETE" }, token),
|
|
runNow: (token: string, id: string) =>
|
|
fetchWithAuth(`/api/v1/queries/${id}/run-now`, { method: "POST" }, token),
|
|
},
|
|
citations: {
|
|
list: (token: string, params?: string) =>
|
|
fetchWithAuth(`/api/v1/citations/${params ? `?${params}` : ""}`, {}, token),
|
|
getStats: (token: string) => fetchWithAuth("/api/v1/citations/stats/", {}, token),
|
|
},
|
|
reports: {
|
|
exportCSV: (token: string, queryId?: string) => {
|
|
const query = queryId ? `?query_id=${queryId}` : "";
|
|
return fetchWithAuth(`/api/v1/reports/export/csv${query}`, {}, token);
|
|
},
|
|
},
|
|
};
|