Skip to content

Repository files navigation

@kwaimind/zodfetch

Type-safe fetch wrapper with Zod validation.

Install

npm install @kwaimind/zodfetch zod

Usage

Uses the same fetch API but with some zod sugar.

import { z } from "zod";
import { zodFetch } from "@kwaimind/zodfetch";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.email(),
});

// GET request
const user = await zodFetch("https://api.example.com/users/123", userSchema);
// => { id: number; name: string; email: string }

// POST request with body
const newUser = await zodFetch("https://api.example.com/users", userSchema, {
  method: "POST",
  body: JSON.stringify({ name: "John", email: "john@example.com" }),
  headers: { "Content-Type": "application/json" }
});
// => { id: number; name: string; email: string }

// Array responses
const usersSchema = z.array(userSchema);
const users = await zodFetch("https://api.example.com/users", usersSchema);
// => Array<{ id: number; name: string; email: string }>

// With custom headers
const user = await zodFetch("https://api.example.com/users/123", userSchema, {
  headers: { Authorization: "Bearer token" }
});
// => { id: number; name: string; email: string }

Error handling

import { ValidationError } from "zod-fetch";

try {
  await zodFetch("https://api.example.com/users/123", userSchema);
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.issues); // Zod validation issues
  }
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors