如何在typescript中使用axios来封装一个HttpClient类
我們通常開始直接在代碼中使用像axios這樣的第三方庫。這沒有錯。但是,在不斷變化的庫,軟件包,版本等世界中,直接使用這些庫API可能會導致代碼不一致。
一個好的做法是創建自己的抽象并將對庫API的調用包裝到包裝器中。這將使您保持代碼更加一致,并且在將來需要時也可以更輕松地切換到其他庫或者程序包。這是因為您將所有對第三方庫的調用都包裝在一個位置,并且只要包裝器接口沒有更改,就可以替換包裝器方法的實現以切換到新庫。
讓我們開始寫代碼
在用于發出Http請求的代碼的特定情況下,我們可以創建一個名為IHttpClient的接口,然后創建一個名為HttpClient的類來實現該接口。在我們的HttpClient方法中,我們將調用axios方法。
現在,讓我們假設HttpClient僅具有通用的get和post方法:
export interface IHttpClient {get<T>(parameters: IHttpClientRequestParameters): Promise<T>post<T>(parameters: IHttpClientRequestParameters): Promise<T> }我們還需要一個接口,以將我們的參數傳遞給帶有一個參數的get和post,以避免代碼混亂。我們將其稱為IHttpClientRequestParameters,它將花費一些通用時間T來定義傳入的有效負載的類型(如果有)以及用于任何類型的Http請求的其他通用參數:
export interface IHttpClientRequestParameters<T> {url: stringrequiresToken: booleanpayload?: T }這是請求參數接口的每個屬性的詳細說明:
url:這是我們需要向其發出請求的API端點的完整url(必須包含查詢字符串參數)
requireToken:這是一個布爾值,指示我們的請求是否還必須添加身份驗證令牌(即Jwt令牌)
有效負載:這是POST或PUT請求的有效負載,因此是可選的?,F在,我們可以編碼HttpClient類,以實現IHttpClient接口并使用axios。首先,從axios導入所需的內容,并編寫尚未實現的HttpClient類的初始聲明:
import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'export class HttpClient implements IHttpClient {// ... implementation code will go here }現在,按照界面中的定義添加get方法的實現。請注意,這里我使用的是Promise語法,但是歡迎您使用async / await語法。我們的get方法將使用IHttpClientRequestParameters的實例并返回Promise:
get<T>(parameters: IHttpClientRequestParameters): Promise<T> {return new Promise<T>((resolve, reject) => {// extract the individual parametersconst { url, requiresToken } = parameters // axios request options like headers etcconst options: AxiosRequestConfig = {headers: {}}// if API endpoint requires a token, we'll need to add a way to add this.if (requiresToken) {const token = this.getToken()options.headers.RequestVerificationToken = token}// finally execute the GET request with axios:axios.get(url, options).then((response: any) => {resolve(response.data as T)}).catch((response: any) => {reject(response)})}) }同樣,現在添加接口中定義的post方法的實現。像get一樣,我們的post方法將采用IHttpClientRequestParameters的實例并返回Promise:
post<T>(parameters: IHttpClientRequestParameters): Promise<T> {return new Promise<T>((resolve, reject) => {const { url, payload, requiresToken } = parameters// axios request options like headers etcconst options: AxiosRequestConfig = {headers: {}}// if API endpoint requires a token, we'll need to add a way to add this.if (requiresToken) {const token = this.getToken()options.headers.RequestVerificationToken = token}// finally execute the GET request with axios:axios.post(url, payload, options).then((response: any) => {resolve(response.data as T)}).catch((response: any) => {reject(response)})}) }現在,您可以導出HttpClient的實例并在整個代碼中使用:
export const httpClient = new HttpClient()這是一個示例,我們使用它來獲取IItem類型的“項目”列表:
fetchItems(): Promise<IItem[]> {// prepare our request parametersconst getParameters: IHttpClientPostParameters = {url: 'http://yourapiurl/items',requiresToken: false}// just return httpClient.get (which is a promise) or again use async/await if you preferreturn httpClient.get<IItem[]>(getParameters) }總結
現在,您有了一個HttpClient,它抽象了不同的Http請求(如get或post等)并將代碼封裝在一個地方。在HttpClient中,您可以使用axios或者其他平臺的請求庫亦或其他請求協議,這樣并不會污染你外部的代碼。
總結
以上是生活随笔為你收集整理的如何在typescript中使用axios来封装一个HttpClient类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CSS实现TikTok文字抖动效果
- 下一篇: gRPC Web使用指南