's'
This commit is contained in:
29
services/api-client.ts
Normal file
29
services/api-client.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user