0.3.1 • Published 1 year ago

@darthrommy/zodfetch v0.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

ZodFetch

This is a simple fetch() wrapper extended by type validation of responses using zod.

Installation

To install, hit the following command:

npm i @darthrommy/zodfetch

This package requires zod as a peer dependency, so you also need to install it too.

npm i zod

Basic Usage

If you know how to use both fetch and zod, you won't find it hard to use. You need to:

  • Pass zod schema as the first argument (required)
  • Pass url as the second argument (required)
  • Pass RequestInit object as the last argument (optional)
import { z } from "zod";
import { zodFetch } from "@darthrommy/zodfetch";

// creating zod schema
const schema = z.object({
  message: z.string(),
});

const { data } = await zodFetch(schema, "https://api.example.com", {
  method: "GET",
  headers: {
    "content-type": "application/json",
  },
});

API

What zodFetch does is just fetch, validate its response body, and returns data as a axios-like interface.

zodFetch(schema, input, init?)

This is a wrapper of the schema.parse() method.

schema

A zod schema to validate. See Zod Docs.

input

A fetch input. (e.g. https://example.com/api)

init

A RequestInit object. (e.g. headers, body, method...)

returns

data

A response body you expect.

status

A status code of the response.

statusText

A status text of the response.

headers

A Headers object of the response.

type ZodFetch = <T>(
  schema: z.ZodType<T>,
  input: RequestInfo | URL,
  init?: RequestInit
) => Promise<{
  data: T;
  status: number;
  statusText: string;
  headers: Headers;
}>;

Error Handling

The schema.parse() may throw ZodError, so you need to try-catch if you want to handle validation error. If you want to handle without try-catch, I recommend zodSafeFetch.

try {
  const { data } = await zodFetch(schema, url); // May throw error
  return res.status(200).json(data);
} catch (e) {
  return res.status(500).end();
}

zodSafeFetch(schema, input, init?)

This is a wrapper of the schema.safeParse() method.

args

same as the zodFetch.

returns

data
  • { success: true, data: T } if the body is valid.
  • { success: false, error: ZodError } if invalid.

See safeParse() Docs.

the rest of the returns

same as the zodFetch.

type ZodSafeFetch = <T>(
  schema: z.ZodType<T>,
  input: RequestInfo | URL,
  init?: RequestInit
) => Promise<{
  result: z.SafeParseReturnType<T, T>;
  status: number;
  statusText: string;
  headers: Headers;
}>;
0.3.1

1 year ago

0.3.0

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago