Created
July 10, 2024 19:54
-
-
Save WomB0ComB0/3df9cfddea01c9aebc54a890113260bb to your computer and use it in GitHub Desktop.
TypeSafe http requests with zod validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from "zod"; | |
import { PostSchema } from "@/schema/posts"; | |
import { CommentsSchema } from "@/schema/comments"; | |
export function createAPIClient() { | |
async function _fetch<T extends z.ZodTypeAny>( | |
input: RequestInfo, | |
init: RequestInit, | |
type: T | |
): Promise<z.infer<T>> { | |
const headers = new Headers(init?.headers); | |
const res = await fetch(input, { ...init, headers }); | |
if (!res.ok) { | |
throw new Error(res.statusText); | |
} | |
const data = await res.json(); | |
const result = await type.safeParseAsync(data); | |
if (!result.success) { | |
throw new Error(result.error.message); | |
} | |
return result.data; | |
} | |
return { | |
posts: { | |
get: (slug: string) => _fetch(`/api/posts/${slug}`, { method: "GET" }, PostSchema), | |
getAll: () => _fetch('/api/posts', { method: 'GET' }, z.array(PostSchema)), | |
post: { | |
create: (post: z.infer<typeof PostSchema>) => _fetch('/api/v1/posts', { method: 'POST' }, PostSchema), | |
update: (post: z.infer<typeof PostSchema>) => _fetch(`/api/v1/posts/${post.id}`, { method: 'PUT', body: JSON.stringify(post) }, PostSchema), | |
delete: (postId: string) => _fetch(`/api/v1/posts/${postId}`, { method: 'DELETE' }, z.object({ success: z.boolean() })), | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment