@maxtan/fetch
v1.0.1
Published
基于ofetch封装的fetch库
Readme
Fetch
基于 ofetch 封装的轻量请求库,纯 ESM 产物。提供实例级默认配置、请求方法快捷方式与 TypeScript 泛型透传,其余能力(自动 JSON、拦截器、重试、超时等)由 ofetch 原生提供。
安装
pnpm add @maxtan/fetchofetch 为 peer 依赖(^1.5.1),请确保项目内已安装:
pnpm add ofetch使用
import { Http } from '@maxtan/fetch'
const http = new Http({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { Authorization: 'Bearer token' },
})
// GET:第二个参数序列化为 query string → /user?page=1&size=10
const users = await http.get('/user', { page: 1, size: 10 })
// POST / PUT / DELETE:第二个参数作为请求体(自动 JSON 序列化)
await http.post('/user', { name: 'sino' })
await http.put('/user/1', { name: 'sino' })
await http.delete('/user/1', { soft: true })派生实例
create 基于当前实例的 options 复制派生新实例,适合在共用基础配置上扩展出各业务域实例,且互不影响:
const base = new Http({ baseURL: 'https://api.example.com', timeout: 10000 })
const userHttp = base.create({ baseURL: 'https://user.example.com' })
const payHttp = base.create({ headers: { 'X-Channel': 'app' } })
// base 自身保持不变配置合并规则
- 请求级 options 与实例 options 浅合并,同名键以请求级为准
- 实例 options 修改后对后续请求生效(
http.options.timeout = 3000)
const http = new Http({ baseURL: 'https://a.com', timeout: 1000 })
// 单次请求覆盖超时
await http.get('/user', {}, { timeout: 5000 })响应类型
通过第二个泛型 R 透传 ofetch 的 responseType(默认 'json',返回值自动按 JSON 解析):
import type { FetchOptions } from '@maxtan/fetch'
const text = await http.request<string, 'text'>('/file', { responseType: 'text' })
const blob = await http.get<Blob, 'blob'>('/avatar/1', {}, { responseType: 'blob' })可选值:'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream'
ofetch 原生能力
实例与请求级 options 均为 ofetch 的 FetchOptions,拦截器、重试等能力直接可用:
const http = new Http({
baseURL: 'https://api.example.com',
retry: 2,
onRequest({ options }) {
options.headers.set('Authorization', 'Bearer token')
},
onResponseError({ response }) {
console.error('请求失败', response.status)
},
})错误处理
响应状态非 2xx 时 ofetch 抛出 FetchError(含 response、data 等字段),按需捕获:
try {
await http.post('/user', { name: 'sino' })
} catch (e) {
if (e?.response?.status === 401) {
// 跳转登录等处理
}
}如需自行处理非 2xx 响应而不抛错,可在 options 中设置 ignoreResponseErrors: true。
API
| 方法 | 说明 |
| ------------------------------------------- | ------------------------------------------- |
| new Http(options?) | 创建实例,options 为实例级默认配置 |
| http.create(options): Http | 基于当前实例 options 派生新实例 |
| http.request<T, R>(url, options?) | 自定义请求,options.method 等由调用方指定 |
| http.get<T, R>(url, query?, options?) | GET,query 序列化为查询参数 |
| http.post<T, R>(url, params?, options?) | POST,params 作为请求体 |
| http.put<T, R>(url, params?, options?) | PUT,params 作为请求体 |
| http.delete<T, R>(url, params?, options?) | DELETE,params 作为请求体 |
T:返回值类型(默认any)R:responseType,默认'json'FetchOptions类型自 ofetch 透传导出,供消费方标注变量
