Files
wagtailcms-frontend/services/api-client.ts
T

47 lines
1.2 KiB
TypeScript

/**
* Wagtail API v2 请求客户端。
* 详见 documents/设计方案分析与完善版.md §2.7 Headless API 设计规范。
*/
const PUBLIC_API_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
const API_BASE_URL = typeof window === "undefined"
? process.env.API_INTERNAL_URL || PUBLIC_API_URL
: PUBLIC_API_URL;
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: path.startsWith("/api/v2/pages/")
? [...new Set(["wagtail-pages", ...(tags ?? [])])]
: tags,
},
});
if (!res.ok) {
throw new ApiError(`API request failed: ${path}`, res.status);
}
return res.json() as Promise<T>;
}