39 lines
946 B
TypeScript
39 lines
946 B
TypeScript
/**
|
|
* Wagtail API v2 请求客户端。
|
|
* 详见 documents/设计方案分析与完善版.md §2.7 Headless API 设计规范。
|
|
*/
|
|
|
|
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
|
|
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public status: number,
|
|
) {
|
|
super(message);
|
|
this.name = "ApiError";
|
|
}
|
|
}
|
|
|
|
interface FetchOptions {
|
|
/** ISR 重新验证秒数,默认 60s。传 0 表示不缓存(用于预览)。 */
|
|
revalidate?: number;
|
|
/** 关联的缓存标签,供 revalidateTag 精准失效使用。 */
|
|
tags?: string[];
|
|
}
|
|
|
|
export async function fetchAPI<T>(
|
|
path: string,
|
|
{ revalidate = 60, tags }: FetchOptions = {},
|
|
): Promise<T> {
|
|
const res = await fetch(`${API_BASE_URL}${path}`, {
|
|
next: { revalidate, tags },
|
|
});
|
|
|
|
if (!res.ok) {
|
|
throw new ApiError(`API request failed: ${path}`, res.status);
|
|
}
|
|
|
|
return res.json() as Promise<T>;
|
|
}
|