0.1.1 • Published 3 years ago
simple-axios v0.1.1
simple-axios
基于axios的开发的扩展请求包,在axios的基础上扩展了一些请求相关的辅助函数, 使开发时把更多的精力关注在业务本身上, 简化请求调用的复杂性。
安装
yarn add simple-axios
npm install simple-axios --save
设计目的
1.统一所有请求方法的入参规则, 第一个参数为url, 第二个参数为携带的请求参数, 第三个参数为请求配置项
2.方法语义化和责任点分离,
get
| head
| options
| delete
方法只关心数据返回类型, 例如需要接收一个blob
类型, 调用getBlob
即可
post
| put
| patch
方法只关心数据的传输格式(编码方式), 比如需要提交一个表单, 调用postMultipart
即可
download
方法传入url,或者blob对象即可完成下载本地的操作。
3.对请求方法本身进行增强, 例如fetch相关的请求会带上时间戳避免缓存问题, modify相关的请求会自动使用qs
库进行序列化数据。
4.适配跨平台的场景, axios自适应node和browser两个平台, 如需要适配如微信小程序, uni-app等其他平台, 也可以在此包中扩展。
快速开始
import { createAxios } from 'simple-axios'
const axios = createAxios(/** @see http://www.axios-js.com/zh-cn/docs/#axios-create-config **/)
axios.helpers.get('/api/mock.json', { id: 1 }, /** @see http://www.axios-js.com/zh-cn/docs/#%E8%AF%B7%E6%B1%82%E9%85%8D%E7%BD%AE **/)
函数签名
// 'get' | 'head' | 'options' | 'delete'
export type FetchHelper = <T = any, R = AxiosResponse<T>>(url: string, params?: any, config?: AxiosRequestConfig) => Promise<R>
// 'post' | 'put' | 'patch'
export type ModifyHelper = <T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig) => Promise<R>
export interface AxiosHelpers {
// 获取json格式数据
get: FetchHelper
// 获取blob格式数据,可用于浏览器下构造URL下载
getBlob: FetchHelper
// 获取html文档, 返回一个dom节点, 可直接嵌入文档
getDocument: FetchHelper
// 获取文本
getText: FetchHelper
// 获取Arraybuffer, 可用于分段下载
getArraybuffer: FetchHelper
// 获取可读流, 可用于浏览器缓存
getStream: FetchHelper
head: FetchHelper
headBlob: FetchHelper
headDocument: FetchHelper
headText: FetchHelper
headArraybuffer: FetchHelper
headStream: FetchHelper
options: FetchHelper
optionsBlob: FetchHelper
optionsDocument: FetchHelper
optionsText: FetchHelper
optionsArraybuffer: FetchHelper
optionsStream: FetchHelper
delete: FetchHelper
deleteBlob: FetchHelper
deleteDocument: FetchHelper
deleteText: FetchHelper
deleteArrayBuffer: FetchHelper
deleteStream: FetchHelper
// 提交application/x-www-form-urlencoded编码的数据包
post: ModifyHelper
// 提交application/json编码的数据包
postJSON: ModifyHelper
// 提交multipart/form-data编码的数据包
postMultipart: ModifyHelper
put: ModifyHelper
putJSON: ModifyHelper
putMultipart: ModifyHelper
patch: ModifyHelper
patchJSON: ModifyHelper
patchMultipart: ModifyHelper
// 浏览器下载文件
download(blob: string | Blob, filename: string): void
}