Files
gitlab-instance-0a899031_do…/services/api-client.ts
2026-04-02 07:15:42 -05:00

30 lines
659 B
TypeScript

import { z, ZodSchema } from "zod";
interface ApiClientOptions<TSchema extends ZodSchema> {
endpoint: string;
schema: TSchema;
init?: RequestInit;
}
export async function requestWithSchema<TSchema extends ZodSchema>({
endpoint,
schema,
init,
}: ApiClientOptions<TSchema>): Promise<z.infer<TSchema>> {
const res = await fetch(endpoint, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
next: { revalidate: 60 },
});
if (!res.ok) {
throw new Error(`API 请求失败: ${res.status} ${res.statusText}`);
}
const json = await res.json();
return schema.parse(json);
}