@ct0/zod-fetch
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

@ct0/zod-fetch

通过 API 调用得到的数据往往缺少 ts 类型,解决方法一般是有两种

  1. 人工编写 types 声明文件
  2. 工具生成接口对应的描述文件

这样处理以后,得到的是静态类型标记。可能存在的问题

  1. 标记类型与实际类型不符
  2. 因为生成工具的问题,导致生成的标记类型异常

从以上问题出发,提出了一种方法,使用兼容 ts 类型的运行时类型校验,来编写接口校验方法,省略了接口类型静态声明,还能保证运行时的类型正确。

底层依赖 2 个功能

  • zod: 运行时类型校验库
  • fetch: 内置 ajax 请求方法

Installation

npm i @ct0/zod-fetch

Usage

// 引用创建方法
import { create } from "@ct0/zod-fetch";
// 使用前必须新建实例
const api = create();
// 一个项目中不同的请求配置可以创建不同的实例,使用不同的插件

Example

例子:获取用户信息

import { create } from "@ct0/zod-fetch";
import z from "zod";

api = create("/api");

function getUser() {
  const schema = z.object({
    id: z.number(),
    name: z.string(),
  });
  return api.Get(schema)("/user/info");
}

添加插件

import { create } from "@ct0/zod-fetch";

// 创建实例后,
const { use, Get, Post, Put, Delete } = create("/api", [
  {
    name: "plugin name",
    request: (init) => {
      // 这里可以修改用于发送请求的配置
      // 配置参数 https://developer.mozilla.org/zh-CN/docs/Web/API/fetch#init
      return init;
    },
    response: (data) => {
      /* 
        这里处理返回的数据,注意:每个插件的输入来自上一个插件的输出,
        第一个插件的输入是 http 的 Response
        */
      return data;
    },
  },
]);

// 还可以添加新插件
// 下面插件,标记发送请求的内容都是 json
use({
  name: "new plugin",
  request: (init) => {
    init.headers = {
      "Content-Type": "application/json",
      ...init.headers,
    };
    return init;
  },
});

更多例子,查看 example 目录

TODO

  • [ ] source code
    • [x] index
    • [x] core
    • [x] utils
    • [x] plugins
      • [x] json
  • [ ] docoument
  • [ ] test
  • [ ] refine zod errors
  • [ ] english in everywhere

Readme

Keywords

none

Package Sidebar

Install

npm i @ct0/zod-fetch

Weekly Downloads

10

Version

0.2.0

License

MIT

Unpacked Size

26.3 kB

Total Files

7

Last publish

Collaborators

  • ~luyao
  • tangdaguang
  • delong