This commit is contained in:
commit
db82325ed7
216 files changed
+33718
No files matched your search
@@ -0,0 +1,40 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
export async function api<T = any>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const token = sessionStorage.getItem("session");
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch("/api" + path, {
|
||||
signal: AbortSignal.timeout(15000),
|
||||
...options,
|
||||
headers: {
|
||||
...(options.body instanceof FormData
|
||||
? {}
|
||||
: { "Content-Type": "application/json" }),
|
||||
...(token ? { Authorization: "Bearer " + token } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(503, "无法连接后端服务,请检查服务是否启动");
|
||||
}
|
||||
const data = await res.json().catch(() => ({
|
||||
message:
|
||||
res.status >= 500
|
||||
? "后端服务未就绪,请检查服务与数据库连接"
|
||||
: "服务响应格式异常",
|
||||
}));
|
||||
if (!res.ok)
|
||||
throw new ApiError(res.status, data.message || "操作失败,请稍后重试");
|
||||
return data;
|
||||
}
|
||||
export const body = (v: unknown) => JSON.stringify(v);
|
||||
Reference in new issue
Block a user