up-fetch 开源项目教程
up-fetch Advanced fetch client builder 项目地址: 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 项目地址: https://gitcode.com/gh_mirrors/up/up-fetch
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考