up-fetch 开源项目教程

up-fetch 开源项目教程

up-fetch Advanced fetch client builder up-fetch 项目地址: https://gitcode.com/gh_mirrors/up/up-fetch

1. 项目介绍

up-fetch 是一个先进的 fetch 客户端构建器,它提供了标准模式验证、自动响应解析、智能默认设置等功能。up-fetch 设计的目的是使数据抓取类型安全且对开发者友好,同时保持熟悉的 fetch API 的使用方式。

2. 项目快速启动

首先,您需要安装 up-fetch。使用 npm 进行安装:

npm i up-fetch

创建一个新的 upfetch 实例:

import { up } from 'up-fetch';

export const upfetch = up(fetch);

使用 upfetch 发起一个带有模式验证的请求:

import { upfetch } from './upfetch';
import { z } from 'zod';

const user = await upfetch('https://a.b.c/users/1', {
  schema: z.object({
    id: z.number(),
    name: z.string(),
    avatar: z.string().url(),
  }),
});

// 此时,响应已经被解析并基于模式正确地类型化了。

3. 应用案例和最佳实践

请求配置

您可以在创建实例时为所有请求设置默认值:

const upfetch = up(fetch, () => ({
  baseUrl: 'https://a.b.c',
  timeout: 30000,
}));

简单查询参数

使用原始 fetch:

fetch(`https://api.example.com/todos?search=${search}&skip=${skip}&take=${take}`);

使用 upfetch:

upfetch('/todos', {
  params: { search, skip, take },
});

自动处理请求体

使用原始 fetch:

fetch('https://api.example.com/todos', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ title: 'New Todo' }),
});

使用 upfetch:

upfetch('/todos', {
  method: 'POST',
  body: { title: 'New Todo' },
});

模式验证

up-fetch 支持使用各种模式库进行响应验证,以下是一个使用 zod 的例子:

import { z } from 'zod';

const post = await upfetch('/posts/1', {
  schema: z.object({
    id: z.number(),
    title: z.string(),
  }),
});

生命周期钩子

您可以控制请求/响应的生命周期:

const upfetch = up(fetch, () => ({
  onRequest: (options) => {
    // 请求发送前调用
  },
  onSuccess: (data, options) => {
    // 请求成功完成时调用
  },
  onError: (error, options) => {
    // 请求失败时调用
  },
}));

超时

为单个请求设置超时:

upfetch('/todos', { timeout: 3000 });

为所有请求设置默认超时:

const upfetch = up(fetch, () => ({ timeout: 5000 }));

重试

自动重试失败的请求:

const upfetch = up(fetch, () => ({
  retry: {
    attempts: 3,
    delay: 1000,
  },
}));

重试选项可以在每个请求的基础上覆盖:

await upfetch('/api/data', {
  method: 'DELETE',
  retry: {
    attempts: 3,
    delay: (ctx) => ctx.attempt ** 2 * 1000,
  },
});

错误处理

处理响应错误:

import { isResponseError } from 'up-fetch';

try {
  await upfetch('/todos/1');
} catch (error) {
  if (isResponseError(error)) {
    console.log(error.status);
  }
}

处理模式验证错误:

import { isValidationError } from 'up-fetch';

try {
  await upfetch('/todos/1', { schema: todoSchema });
} catch (error) {
  if (isValidationError(error)) {
    console.log(error.issues);
  }
}

认证

轻松为所有请求添加认证信息:

const upfetch = up(fetch, () => ({
  headers: {
    Authorization: localStorage.getItem('bearer-token'),
  },
}));

4. 典型生态项目

在 up-fetch 的生态中,您可以找到各种扩展和工具,如:

  • up-fetch-zod:用于 zod 模式验证的集成。
  • up-fetch-valibot:用于 valibot 模式验证的集成。
  • up-fetch-arktype:用于 arktype 模式验证的集成。

这些项目可以帮助您更加便捷地使用 up-fetch,并根据您的特定需求进行扩展。

up-fetch Advanced fetch client builder up-fetch 项目地址: https://gitcode.com/gh_mirrors/up/up-fetch

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霍妲思

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值