获取T
类型安全获取 API 包,包含可中止请求,超时支持,进度跟踪,自动重试,以及类似 Rust-Enterpress 错误处理等内容.
特征
- 可中止的请求 - 随时通过
FetchTask.abort() - 类型安全对策 - 指定返回类型
responseType参数(text, (中文(简体) ),json, (中文(简体) ),arraybuffer, (中文(简体) ),bytes, (中文(简体) ),blob, (中文(简体) ),stream(中文(简体) ) - 超时支持 - 指定毫秒后自动执行请求
- 进展跟踪 - 监控下载进度
onProgress回调 - 串流 - 通过原始数据块访问
onChunk回调 - 自动重试 - 可配置的重试策略
retry选项 - 结果错误处理 - 烂透了
Result用于明确错误处理的类型 - 跨平台 - 与Deno、Node.js、Bun和浏览器合作
安装
# npm
npm install @happy-ts/fetch-t
# yarn
yarn add @happy-ts/fetch-t
# pnpm
pnpm add @happy-ts/fetch-t
# JSR (Deno)
deno add @happy-ts/fetch-t
# JSR (Bun)
bunx jsr add @happy-ts/fetch-t
快速启动
基本用途
import { fetchT } from '@happy-ts/fetch-t';
// GET JSON data
const result = await fetchT<{ id: number; title: string }>('https://api.example.com/data', {
responseType: 'json',
});
result.inspect(data => {
console.log(data.title);
}).inspectErr(err => {
console.error('Request failed:', err.message);
});
可中止的请求
const task = fetchT('https://api.example.com/large-file', {
abortable: true,
responseType: 'arraybuffer',
});
// Abort after 5 seconds
setTimeout(() => {
task.abort('User cancelled');
}, 5000);
const result = await task.result;
自动重试
const result = await fetchT('https://api.example.com/data', {
retry: {
retries: 3,
delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),
when: [500, 502, 503, 504],
onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),
},
responseType: 'json',
});
实例
处理错误设计
fetchT 区分两类错误:
编程出错( 同步)
无效的参数会立即抛出故障快速行为 :
// These throw synchronously - no try/catch around await needed
fetchT('https://example.com', { timeout: -1 }); // Error: timeout must be > 0
fetchT('https://example.com', { timeout: 'bad' }); // TypeError: timeout must be a number
fetchT('not-a-url'); // TypeError: Invalid URL
这跟本地不同 fetch,它返回拒绝的参数错误承诺。 同步抛出能提供更清晰的堆栈痕迹,并在开发过程中捕捉到bug.
运行时出错( 结果类型)
网络失败和 HTTP 错误被包入 Result 类型 :
const result = await fetchT('https://api.example.com/data', { responseType: 'json' });
if (result.isErr()) {
const error = result.unwrapErr();
// FetchError with status code, or network Error
}