zod-fetch 中文文档教程

发布于 2年前 浏览 12 更新于 2年前

Zod Fetch

zod-fetch 是一个简单的 API,用于使用 Zod 构建类型和运行时安全的获取器函数模式。

用法

使用默认的 fetcher

您可以使用 createZodFetcher 创建一个 fetcher:

import { z } from "zod";
import { createZodFetcher } from "zod-fetcher";

const fetchWithZod = createZodFetcher();

fetchWithZod(
  // The schema you want to validate with
  z.object({
    hello: "world",
  }),
  // Any parameters you would usually pass to fetch
  "/my-api",
).then((res) => {
  console.log(res);
  //          ^? { hello: string }
});

如果您没有将 fetcher 传递给 createZodFetcher,它会使用一个合理的默认 fetcher(使用 fetch API)来抓取所需的数据。

使用自定义提取器

您可以将自定义提取器传递给 zod-fetcher:

import { z } from "zod";
import { createZodFetcher } from "zod-fetcher";
import axios from "axios";

const fetchWithZod = createZodFetcher(axios.get);

fetchWithZod(
  z.object({
    data: z.object({
      name: z.string(),
    }),
  }),
  "/user",
  {
    params: {
      id: 12345,
    },
  },
).then((res) => {
  console.log(res);
  //          ^? { data: { name: string } }
});

为什么会存在这个?

对于想要将运行时安全性与获取器(一种极其常见的用例)结合起来的团队,您通常有一个选择:

  1. 使用大型、包罗万象的解决方案,例如 tRPC
  2. 自行破解一些东西,

我希望这个小型 API 为希望弥合这一差距的团队提供了一个很好的折衷方案。或者,至少提供了一些漂亮的示例代码,您可以将其复制并粘贴到您的项目中。

Zod Fetch

zod-fetch is a simple API for building a type and runtime-safe fetcher function using Zod schemas.

Usage

Using the default fetcher

You can create a fetcher using createZodFetcher:

import { z } from "zod";
import { createZodFetcher } from "zod-fetcher";

const fetchWithZod = createZodFetcher();

fetchWithZod(
  // The schema you want to validate with
  z.object({
    hello: "world",
  }),
  // Any parameters you would usually pass to fetch
  "/my-api",
).then((res) => {
  console.log(res);
  //          ^? { hello: string }
});

If you don't pass a fetcher to createZodFetcher, it uses a sensible default fetcher (using the fetch API) to grab the data needed.

Using a custom fetcher

You can pass custom fetchers to zod-fetcher:

import { z } from "zod";
import { createZodFetcher } from "zod-fetcher";
import axios from "axios";

const fetchWithZod = createZodFetcher(axios.get);

fetchWithZod(
  z.object({
    data: z.object({
      name: z.string(),
    }),
  }),
  "/user",
  {
    params: {
      id: 12345,
    },
  },
).then((res) => {
  console.log(res);
  //          ^? { data: { name: string } }
});

Why does this exist?

For teams that want to combine runtime-safety with a fetcher (an extremely common use case), you often have a choice:

  1. Use a big, all-encompassing solution like tRPC
  2. Hack something together on your own

I hope that this small API offers a nice compromise for teams looking to bridge that gap. Or, at least, offers some pretty example code you can copy-and-paste into your projects.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文