Typescript?封裝?Axios攔截器方法實例
引言
對 axios 二次封裝,更加的可配置化、擴展性更加強大靈活
通過 class 類實現(xiàn),class 具備更強封裝性(封裝、繼承、多態(tài)),通過實例化類傳入自定義的配置
創(chuàng)建 class
嚴格要求實例化時傳入的配置,擁有更好的代碼提示
/**
* @param {AxiosInstance} axios實例類型
* @param {AxiosRequestConfig} axios配置項類型
*/
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
class Http {
axios: AxiosInstance
constructor(config: AxiosRequestConfig) {
// 創(chuàng)建一個實例 axios.create([config])
this.axios = axios.create(config)
}
}
// 每實例化一個 axios 時,都是不同的 axios 示例,互不干擾
new Http({
baseURL:'qq.com';
timeout:60 * 1
});
new Http({
baseURL:'web.com'
});
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
AxiosRequestConfig 的類型注解
export interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: AxiosRequestHeaders;
params?: any;
paramsSerializer?: (params: any) => string;
data?: D;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: AbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
}
封裝 request(config)通用方法
/**
* axios#request(config)
* @param {*} config
* @returns {*}
*/
request(config: AxiosRequestConfig) {
return this.axios.request(config)
}
?? 在 axios 中,request中的 config 參數(shù)與實例化時,axios.create(config)傳入的參數(shù)是相同的,以下是 axios 方法具體參數(shù)
axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) axios.getUri([config])
封裝-攔截器(單個實例獨享)
攔截器的hooks,在請求或響應被 then 或 catch 處理前攔截處理
??在請求中,如攜帶token、loading動畫、header配置...,都是一些公有的邏輯,所以可以寫到全局的攔截器里面
??注意的是,可能存在某些項目請求,需要的公有的邏輯配置方式不一樣,如 A項目:攜帶token、loading動畫,B項目:攜帶token、header配置
??考慮到攔截方式不一樣,固不能將 class 里的攔截器寫si,所以,需要通過不同的 axios 實例化傳入自定義的 hooks(攔截器),實現(xiàn)單個實例獨享,擴展性更強
在上面實例化 Http(Axios) 時,僅僅傳入 axios 約定好的 config(AxiosRequestConfig)
new Http({
baseURL:'qq.com';
timeout:60 * 1
});
經(jīng)過分析考慮,需要在實例化 Http 時,可以傳入更多自定義的 hooks,擴展 axios。但是,在實例化時,直接傳入定義好的攔截器是不可行的 Why?
new Http({
baseURL: 'qq.com',
timeout: 60 * 1,
hooks: {}, // ERROR ????
interceptor: () => {} // ERROR ????
})
“hooks”不在類型“AxiosRequestConfig<any>”中,在上面 Http class 的 constructor 構造函數(shù)中,嚴格約束傳入的參數(shù)應為AxiosRequestConfig類型(TS)
AxiosRequestConfig 中并不存在 hooks and interceptor類型的屬性(AxiosRequestConfig 是由 axios 提供的一個類型注解)
??擴展 Http 自定義攔截器
對 AxiosRequestConfig 類型注解進行繼承,使得在實例化時,可以傳入擴展后的類型,定義:
???IinterceptorHooks接口存儲自定義的攔截器函數(shù)、
???IHttpRequestConfig接口繼承 AxiosRequestConfig,并擴展自定義攔截器的屬性,屬性類型為:IinterceptorHooks
???`IinterceptorHooks`攔截器Hook接口類型
import type { AxiosResponse, AxiosRequestConfig } from 'axios'
/**
* 攔截器的hooks,在請求或響應被 then 或 catch 處理前攔截
* @param {beforeRequestInterceptor(?)} 發(fā)送請求之前攔截器
* @param {requestErrorInterceptor(?)} 請求錯誤攔截器
* @param {responseSuccessInterceptor(?)} 響應成功攔截器
* @param {responseFailInterceptor(?)} 響應失敗攔截器
*/
interface interceptorHooks {
beforeRequestInterceptor: (config: AxiosRequestConfig) => AxiosRequestConfig
requestErrorInterceptor: (error: any) => any
responseSuccessInterceptor: (result: AxiosResponse) => AxiosResponse
responseFailInterceptor: (error: any) => any
}
export type IinterceptorHooks = Partial<interceptorHooks>
??Partial:Typescript 內(nèi)置類型,將定義的類型注解全部變?yōu)榭蛇x的屬性
??調(diào)用說明:axios.interceptors.request.use( beforeRequestInterceptor , requestErrorInterceptor );
請求之前攔截器中(beforeRequestInterceptor),config 參數(shù)同樣是與axios.create中的參數(shù)類型相同,為AxiosRequestConfig
注意:并不是IHttpRequestConfig
???`IHttpRequestConfig` 類構造函數(shù) config 接口類型
/**
* 實例化Http類的配置項參數(shù),繼承于AxiosRequestConfig
* @param {interceptors(?)} 攔截器Hooks
* @param {loading} 請求loading
* @param {...} 其它的配置項
* @param {AxiosRequestConfig} axios原生的配置選
*/
export interface IHttpRequestConfig extends AxiosRequestConfig {
interceptors?: IinterceptorHooks
}
??使用說明:
import { IHttpRequestConfig, IinterceptorHooks } from './types'
class Http {
axios: AxiosInstance
interceptors?: IinterceptorHooks
constructor(config: IHttpRequestConfig) {
// 解構自定義的屬性
const { interceptors, ...AxiosRequestConfig } = config
this.axios = axios.create(AxiosRequestConfig)
// 存儲自定義攔截Hooks or 直接 use() 使用
this.interceptors = interceptors
// 傳入自定義請求攔截器Hooks
this.axios.interceptors.request.use(
this.interceptors?.beforeRequestInterceptor,
this.interceptors?.requestErrorInterceptor
)
// 傳入自定義響應攔截器Hooks
this.axios.interceptors.response.use(
this.interceptors?.responseSuccessInterceptor,
this.interceptors?.responseFailInterceptor
)
}
}
// 擴展后的實例化...?
interceptors: {
// ... 自定義的攔截Hooks
beforeRequestInterceptor: (config: IHttpRequestConfig) => {
const token = localStorage.getItem('token')
if (token && config.headers) {
config.headers.Authorization = token
}
return config
}
}
封裝-攔截器(所有實例共享)
無論存在多少個實例的 Http,所有實例都會共享的同一套攔截器,在 class 中固定的
class Http {
axios: AxiosInstance
// ...
constructor(config: IHttpRequestConfig) {
// ...單個實例獨享攔截器處理??
// 所有實例共享的攔截-請求攔截器??
this.axios.interceptors.request.use(
function (config) {
// 在發(fā)送請求之前做些什么
return config
},
function (error) {
// 對請求錯誤做些什么
return Promise.reject(error)
}
)
// 所有實例共享的攔截-響應攔截器
this.axios.interceptors.response.use(
function (response) {
// 2xx 范圍內(nèi)的狀態(tài)碼都會觸發(fā)該函數(shù)。
// 對響應數(shù)據(jù)做點什么
return response
},
function (error) {
// 超出 2xx 范圍的狀態(tài)碼都會觸發(fā)該函數(shù)。
// 對響應錯誤做點什么
return Promise.reject(error)
}
)
}
}
封裝-攔截器(單個請求獨享)
在 axios 原生的 config(AxiosRequestConfig) 中,存在兩個允許對請求or響應的數(shù)據(jù)進行轉(zhuǎn)化處理:
// `transformRequest` 允許在向服務器發(fā)送前,修改請求數(shù)據(jù)
// 它只能用于 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 數(shù)組中最后一個函數(shù)必須返回一個字符串, 一個Buffer實例,ArrayBuffer,F(xiàn)ormData,或 Stream
// 你可以修改請求頭。
transformRequest: [function (data, headers) {
// 對發(fā)送的 data 進行任意轉(zhuǎn)換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前,允許修改響應數(shù)據(jù)
transformResponse: [function (data) {
// 對接收的 data 進行任意轉(zhuǎn)換處理
return data;
}],
由于transformRequest、transformResponse為 Axios 原生的API,所以盡量不去改變原有的 config API
??在需要不修改原生 Axios config 情況下,擴展單個請求獨享的攔截器時
??class 封裝的方法:request(config: AxiosRequestConfig){}參數(shù)中不能再使用原生AxiosRequestConfig作為參數(shù)的注解
??前面提到過,request 中的 config 參數(shù)與實例化時傳入的參數(shù)是相同的,所以在這里同樣可以使用IHttpRequestConfig,作為 request 的參數(shù)注解
/**
* axios#request(config)
* @param {*} config
* @returns {*}
*/
request(config: AxiosRequestConfig) {
return this.axios.request(config)
}
// ...改為 AxiosRequestConfig -> IHttpRequestConfig
request(config: IHttpRequestConfig) {
// ... 在執(zhí)行請求之前,執(zhí)行單個請求獨享的攔截器(?)
return this.axios.request(config).then(
// ...
)
}
具體代碼實現(xiàn):
// Http 封裝的request??
request(config: IHttpRequestConfig) {
// 存在單個方法獨享自定義攔截器Hooks(請求之前)??
if (config.interceptors?.beforeRequestInterceptor) {
// 立即執(zhí)行beforeRequestInterceptor方法,傳入config處理返回新的處理后的config
config = config.interceptors.beforeRequestInterceptor(config)
}
return this.axios
.request(config)
.then((result) => {
// 存在單個方法獨享自定義攔截器Hooks(響應成功)??
if (config.interceptors?.responseSuccessInterceptor) {
// 立即執(zhí)行beforeRequestInterceptor方法,傳入config處理返回新的處理后的config
result = config.interceptors.responseSuccessInterceptor(result)
}
return result
})
.catch((error) => {
// 存在單個方法獨享自定義攔截器Hooks(響應失敗)??
if (config.interceptors?.responseFailInterceptor) {
// 立即執(zhí)行beforeRequestInterceptor方法,傳入config處理返回新的處理后的config
error = config.interceptors.responseFailInterceptor(error)
}
return error
})
}
// 執(zhí)行 request 方法,傳入攔截器處理??,如:
axios.request({
url: '/api/addUser',
methed: 'POST',
interceptors: {
beforeRequestInterceptor:(config) => {
// ...處理config數(shù)據(jù)
return config
},
// ...請求錯誤處理不攔截
responseSuccessInterceptor:(result) => {
return result
}
}
})
注意:當存在單個方法獨享自定義請求攔截器時,應當在發(fā)送請求之前立即執(zhí)行 beforeRequestInterceptor 方法,而不是通過傳入到 use() 回調(diào),執(zhí)行請求攔截方法處理完之后返回一個經(jīng)過處理的 config,在傳入到請求方法中,發(fā)送請求
其它的單個方法獨享自定義響應攔截器一樣
裝修 Http class
返回經(jīng)過
在響應數(shù)據(jù)時候(響應攔截器),Axios 為數(shù)據(jù)在外層包裝了一層對象,后臺返回的數(shù)據(jù)就存在于 result 的 data 中,所以需要對數(shù)據(jù)再一步的處理,扒開最外層的皮
注意:Axios 在外層包裝的對象數(shù)據(jù),其實在某些情況下是需要 result 中的一些屬性數(shù)據(jù)的,并不僅僅需要 data,比如返回格式為文件數(shù)據(jù)中,需要 headers 中的一些數(shù)據(jù)對文件進行處理,命名等...
這里的扒皮處理,邏輯應當屬于所有實例共享的一個攔截器,具體工具需要進行處理
// 所有實例共享的攔截-響應攔截器
this.axios.interceptors.response.use(
function (response) {
// 返回為文件流時,直接返回(文件需要單獨處理)??
if (['blob', 'arraybuffer'].includes(response.request.responseType)) {
// if (response.headers['content-disposition']) {
// let fileName = response.headers['content-disposition'].split('filename=')[1]
// fileName = decodeURI(fileName)
// return {
// data: response.data,
// fileName
// }
// }
return response
}
// 根據(jù)業(yè)務碼 or 狀態(tài)碼...進行判斷
// 扒皮??
return response.data
},
function (error) {
// 超出 2xx 范圍的狀態(tài)碼都會觸發(fā)該函數(shù)。
// 對響應錯誤做點什么
return Promise.reject(error)
}
)
request 返回數(shù)據(jù)結構(DTO)
定義返回數(shù)據(jù)類型注解
// 最終數(shù)據(jù)類型注解
interface IDateType {
[key: string]: any
}
// axios 返回的數(shù)據(jù)類型注解,IDateType === T
interface IDTO<T = any> {
code: number
data: T
message: string
state: number
[prop: string]: any
}
// 請求方法,傳入注解
axios.request<IDTO<IDateType>>({
url: '/api/addUser',
methed: 'POST',
})
由于在所有實例共享的響應攔截器中,修改了返回的數(shù)據(jù)結構return response.data,到達方法響應攔截器中的數(shù)據(jù)類型已經(jīng)不再是AxiosResponse,導致在響應成功的攔截器中類型錯誤無法賦值,以及.then返回的類型不正確無法返回,正確應該為DTO類型,解決方案:
// 修改 AxiosRequestConfig 類型注解,默認類型為原來的 AxiosResponse,傳遞到響應成功的攔截中進行泛型注解,用于在方法中重新修改返回的數(shù)據(jù)類型
// 最終的泛型類型注解到達 responseSuccessInterceptor 中
interface interceptorHooks<T> {
beforeRequestInterceptor: (config: AxiosRequestConfig) => AxiosRequestConfig
requestErrorInterceptor: (error: any) => any
responseSuccessInterceptor: (result: T) => T
responseFailInterceptor: (error: any) => any
}
export type IinterceptorHooks<T = AxiosResponse> = Partial<interceptorHooks<T>>
export interface IHttpRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: IinterceptorHooks<T>
}
// 修改 Http class request方法,通過 泛型 T 接受方法傳達過來的 DTO 類型注解,傳遞到 IHttpRequestConfig 中修改 responseSuccessInterceptor 的參數(shù)類型注解以及返回值注解,在單個方法獨享自定義攔截器中就可以接受參數(shù),并且返回正確的 DTO 類型數(shù)據(jù)
// 由于在下面的 this.axios.request() 方法中,返回的數(shù)據(jù)已經(jīng)被上一個攔截器扒皮修改了,返回的 result 類型注解中存在類型不正確情況(正確返回應返回response.data的類型注解),實際返回為 AxiosResponse<any,any>類型注解,導致數(shù)據(jù)返回到最外層方法時編輯器報錯(最外層接受 DTO 類型),所以需要手動修改this.axios.request() 方法中返回的類型注解 this.axios.request<any, T>()
request<T>(config: IHttpRequestConfig<T>): Promise<T> {
return this.axios
.request<any, T>(config)
.then((result) => {
// 存在單個方法獨享自定義攔截器Hooks(響應成功)
if (config.interceptors?.responseSuccessInterceptor) {
// 立即執(zhí)行beforeRequestInterceptor方法,傳入config處理返回新的處理后的config
result = config.interceptors.responseSuccessInterceptor(result)
}
return result
})
.catch((error) => {
// ...
})
}
攔截器執(zhí)行順序
由于在 constructor(構造函數(shù)) 代碼順序:單個實例獨享攔截器 -> 所有實例共享攔截器 ->...
??單個實例獨享攔截器位于所有實例共享攔截器之前,執(zhí)行順序為:
所有實例共享請求攔截器 -> 單個實例獨享請求攔截器 -> 單個實例獨享響應攔截器 -> 所有實例共享響應攔截器
反之,則:
??所有實例共享攔截器位于之前單個實例獨享攔截器,執(zhí)行順序為:
單個實例獨享請求攔截器 -> 所有實例共享請求攔截器 -> 所有實例共享響應攔截器 -> 單個實例獨享響應攔截器
??單個方法獨享攔截器(單個實例獨享攔截器位于所有實例共享攔截器之前) ,執(zhí)行順序為:
單個方法請求攔截器 -> 實例共享請求攔截器 -> 單個獨享請求攔截器 -> 單個獨享響應攔截器 -> 實例共享響應攔截器 -> 單個方法響應攔截器
請求攔截:constructor先執(zhí)行的代碼(use()),攔截器里面的回調(diào)hook后被執(zhí)行,反之,先被執(zhí)行
響應攔截:constructor先執(zhí)行的代碼(use()),攔截器里面的回調(diào)hook先被執(zhí)行,反之,后被執(zhí)行
需要修改執(zhí)行順序可調(diào)整代碼的執(zhí)行順序
操作場景控制
由于存在三種攔截器,存在一些復雜的操作場景時,比如,通過給所有實例或者單獨實例提前添加了操作loading、錯誤捕獲...,但是現(xiàn)在需要在某個請求方法中不進行此操作時,如何解決?
解決方案:通過繼續(xù)擴展特定的 IHttpRequestConfig 類型屬性,因為單個方法請求攔截器是最先執(zhí)行的,IHttpRequestConfig 配置項,在所有的攔截器中是共享的,層級傳遞的,在攔截器中判斷特定的屬性值關閉不需要的操作
以上就是Typescript 封裝 Axios攔截器方法實例的詳細內(nèi)容,更多關于Typescript 封裝 Axios的資料請關注腳本之家其它相關文章!
相關文章
微信小程序上滑加載下拉刷新(onscrollLower)分批加載數(shù)據(jù)(二)
這篇文章主要介紹了微信小程序上滑加載下拉刷新(onscrollLower)分批加載數(shù)據(jù)的相關資料,需要的朋友可以參考下2017-05-05
document 和 document.all 分別什么時候用
document 和 document.all 分別什么時候用...2006-06-06
gulp-font-spider實現(xiàn)中文字體包壓縮實踐
這篇文章主要為大家介紹了gulp-font-spider實現(xiàn)中文字體包壓縮實踐詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03

