30 lines
659 B
TypeScript
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);
|
|
}
|