溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Typescript封裝axios

發(fā)布時(shí)間:2022-07-12 10:23:23 來源:億速云 閱讀:257 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“如何使用Typescript封裝axios”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“如何使用Typescript封裝axios”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

    基礎(chǔ)封裝

    首先我們實(shí)現(xiàn)一個(gè)最基本的版本,實(shí)例代碼如下:

    // index.ts
    import axios from 'axios'
    import type { AxiosInstance, AxiosRequestConfig } from 'axios'
    class Request {
      // axios 實(shí)例
      instance: AxiosInstance
      constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config)
      }
      request(config: AxiosRequestConfig) {
        return this.instance.request(config)
      }
    }
    export default Request

    這里將其封裝為一個(gè)類,而不是一個(gè)函數(shù)的原因是因?yàn)轭惪梢詣?chuàng)建多個(gè)實(shí)例,適用范圍更廣,封裝性更強(qiáng)一些。

    攔截器封裝

    首先我們封裝一下攔截器,這個(gè)攔截器分為三種:

    • 類攔截器

    • 實(shí)例攔截器

    • 接口攔截器

    接下來我們就分別實(shí)現(xiàn)這三個(gè)攔截器。

    類攔截器

    類攔截器比較容易實(shí)現(xiàn),只需要在類中對(duì)axios.create()創(chuàng)建的實(shí)例調(diào)用interceptors下的兩個(gè)攔截器即可,實(shí)例代碼如下:

    // index.ts
    constructor(config: AxiosRequestConfig) {
      this.instance = axios.create(config)
      this.instance.interceptors.request.use(
        (res: AxiosRequestConfig) => {
          console.log('全局請(qǐng)求攔截器')
          return res
        },
        (err: any) => err,
      )
      this.instance.interceptors.response.use(
        // 因?yàn)槲覀兘涌诘臄?shù)據(jù)都在res.data下,所以我們直接返回res.data
        (res: AxiosResponse) => {
          console.log('全局響應(yīng)攔截器')
          return res.data
        },
        (err: any) => err,
      )
    }

    我們?cè)谶@里對(duì)響應(yīng)攔截器做了一個(gè)簡單的處理,就是將請(qǐng)求結(jié)果中的.data進(jìn)行返回,因?yàn)槲覀儗?duì)接口請(qǐng)求的數(shù)據(jù)主要是存在在.data中,跟data同級(jí)的屬性我們基本是不需要的。

    實(shí)例攔截器

    實(shí)例攔截器是為了保證封裝的靈活性,因?yàn)槊恳粋€(gè)實(shí)例中的攔截后處理的操作可能是不一樣的,所以在定義實(shí)例時(shí),允許我們傳入攔截器。

    首先我們定義一下interface,方便類型提示,代碼如下:

    // types.ts
    import type { AxiosRequestConfig, AxiosResponse } from 'axios'
    export interface RequestInterceptors {
      // 請(qǐng)求攔截
      requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
      requestInterceptorsCatch?: (err: any) => any
      // 響應(yīng)攔截
      responseInterceptors?: (config: AxiosResponse) => AxiosResponse
      responseInterceptorsCatch?: (err: any) => any
    }
    // 自定義傳入的參數(shù)
    export interface RequestConfig extends AxiosRequestConfig {
      interceptors?: RequestInterceptors
    }

    定義好基礎(chǔ)的攔截器后,我們需要改造我們傳入的參數(shù)的類型,因?yàn)閍xios提供的AxiosRequestConfig是不允許我們傳入攔截器的,所以說我們自定義了RequestConfig,讓其繼承與AxiosRequestConfig 。

    剩余部分的代碼也比較簡單,如下所示:

    // index.ts
    import axios, { AxiosResponse } from 'axios'
    import type { AxiosInstance, AxiosRequestConfig } from 'axios'
    import type { RequestConfig, RequestInterceptors } from './types'
    class Request {
      // axios 實(shí)例
      instance: AxiosInstance
      // 攔截器對(duì)象
      interceptorsObj?: RequestInterceptors
      constructor(config: RequestConfig) {
        this.instance = axios.create(config)
        this.interceptorsObj = config.interceptors
        this.instance.interceptors.request.use(
          (res: AxiosRequestConfig) => {
            console.log('全局請(qǐng)求攔截器')
            return res
          },
          (err: any) => err,
        )
        // 使用實(shí)例攔截器
        this.instance.interceptors.request.use(
          this.interceptorsObj?.requestInterceptors,
          this.interceptorsObj?.requestInterceptorsCatch,
        )
        this.instance.interceptors.response.use(
          this.interceptorsObj?.responseInterceptors,
          this.interceptorsObj?.responseInterceptorsCatch,
        )
        // 全局響應(yīng)攔截器保證最后執(zhí)行
        this.instance.interceptors.response.use(
          // 因?yàn)槲覀兘涌诘臄?shù)據(jù)都在res.data下,所以我們直接返回res.data
          (res: AxiosResponse) => {
            console.log('全局響應(yīng)攔截器')
            return res.data
          },
          (err: any) => err,
        )
      }
    }

    我們的攔截器的執(zhí)行順序?yàn)閷?shí)例請(qǐng)求→類請(qǐng)求→實(shí)例響應(yīng)→類響應(yīng);這樣我們就可以在實(shí)例攔截上做出一些不同的攔截,

    接口攔截

    現(xiàn)在我們對(duì)單一接口進(jìn)行攔截操作,首先我們將AxiosRequestConfig類型修改為RequestConfig允許傳遞攔截器;

    然后我們?cè)陬悢r截器中將接口請(qǐng)求的數(shù)據(jù)進(jìn)行了返回,也就是說在request()方法中得到的類型就不是AxiosResponse類型了。

    我們查看axios的index.d.ts中,對(duì)request()方法的類型定義如下:

    // type.ts
    request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;

    也就是說它允許我們傳遞類型,從而改變request()方法的返回值類型,我們的代碼如下:

    // index.ts
    request<T>(config: RequestConfig): Promise<T> {
      return new Promise((resolve, reject) => {
        // 如果我們?yōu)閱蝹€(gè)請(qǐng)求設(shè)置攔截器,這里使用單個(gè)請(qǐng)求的攔截器
        if (config.interceptors?.requestInterceptors) {
          config = config.interceptors.requestInterceptors(config)
        }
        this.instance
          .request<any, T>(config)
          .then(res => {
            // 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
            if (config.interceptors?.responseInterceptors) {
              res = config.interceptors.responseInterceptors<T>(res)
            }
            resolve(res)
          })
          .catch((err: any) => {
            reject(err)
          })
      })
    }

    這里還存在一個(gè)細(xì)節(jié),就是我們?cè)跀r截器接受的類型一直是AxiosResponse類型,而在類攔截器中已經(jīng)將返回的類型改變,所以說我們需要為攔截器傳遞一個(gè)泛型,從而使用這種變化,修改types.ts中的代碼,示例如下:

    // index.ts
    export interface RequestInterceptors {
      // 請(qǐng)求攔截
      requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
      requestInterceptorsCatch?: (err: any) => any
      // 響應(yīng)攔截
      responseInterceptors?: <T = AxiosResponse>(config: T) => T
      responseInterceptorsCatch?: (err: any) => any
    }

    請(qǐng)求接口攔截是最前執(zhí)行,而響應(yīng)攔截是最后執(zhí)行。

    封裝請(qǐng)求方法

    現(xiàn)在我們就來封裝一個(gè)請(qǐng)求方法,首先是類進(jìn)行實(shí)例化示例代碼如下:

    // index.ts
    import Request from './request'
    const request = new Request({
      baseURL: import.meta.env.BASE_URL,
      timeout: 1000 * 60 * 5,
      interceptors: {
        // 請(qǐng)求攔截器
        requestInterceptors: config => {
          console.log('實(shí)例請(qǐng)求攔截器')
          return config
        },
        // 響應(yīng)攔截器
        responseInterceptors: result => {
          console.log('實(shí)例響應(yīng)攔截器')
          return result
        },
      },
    })

    然后我們封裝一個(gè)請(qǐng)求方法, 來發(fā)送網(wǎng)絡(luò)請(qǐng)求,代碼如下:

    // src/server/index.ts
    import Request from './request'
    import type { RequestConfig } from './request/types'
    interface YWZRequestConfig<T> extends RequestConfig {
      data?: T
    }
    interface YWZResponse<T> {
      code: number
      message: string
      data: T
    }
    /**
     * @description: 函數(shù)的描述
     * @interface D 請(qǐng)求參數(shù)的interface
     * @interface T 響應(yīng)結(jié)構(gòu)的intercept
     * @param {YWZRequestConfig} config 不管是GET還是POST請(qǐng)求都使用data
     * @returns {Promise}
     */
    const ywzRequest = <D, T = any>(config: YWZRequestConfig<D>) => {
      const { method = 'GET' } = config
      if (method === 'get' || method === 'GET') {
        config.params = config.data
      }
      return request.request<YWZResponse<T>>(config)
    }
    export default ywzRequest

    該請(qǐng)求方式默認(rèn)為GET,且一直用data作為參數(shù);

    取消請(qǐng)求

    應(yīng)評(píng)論區(qū)@Pic、@Michaelee@Alone_Error的建議,這里增加了一個(gè)取消請(qǐng)求;關(guān)于什么是取消請(qǐng)求可以參考官方文檔。

    準(zhǔn)備工作

    我們需要將所有請(qǐng)求的取消方法保存到一個(gè)集合(這里我用的數(shù)組,也可以使用Map)中,然后根據(jù)具體需要去調(diào)用這個(gè)集合中的某個(gè)取消請(qǐng)求方法。

    首先定義兩個(gè)集合,示例代碼如下:

    // index.ts
    import type {
      RequestConfig,
      RequestInterceptors,
      CancelRequestSource,
    } from './types'
    class Request {
      /*
      存放取消方法的集合
      * 在創(chuàng)建請(qǐng)求后將取消請(qǐng)求方法 push 到該集合中
      * 封裝一個(gè)方法,可以取消請(qǐng)求,傳入 url: string|string[] 
      * 在請(qǐng)求之前判斷同一URL是否存在,如果存在就取消請(qǐng)求
      */
      cancelRequestSourceList?: CancelRequestSource[]
      /*
      存放所有請(qǐng)求URL的集合
      * 請(qǐng)求之前需要將url push到該集合中
      * 請(qǐng)求完畢后將url從集合中刪除
      * 添加在發(fā)送請(qǐng)求之前完成,刪除在響應(yīng)之后刪除
      */
      requestUrlList?: string[]
      constructor(config: RequestConfig) {
        // 數(shù)據(jù)初始化
        this.requestUrlList = []
        this.cancelRequestSourceList = []
      }
    }

    這里用的CancelRequestSource接口,我們?nèi)ザx一下:

    // type.ts
    export interface CancelRequestSource {
      [index: string]: () => void
    }

    這里的key是不固定的,因?yàn)槲覀兪褂?code>url做key,只有在使用的時(shí)候才知道url,所以這里使用這種語法。

    取消請(qǐng)求方法的添加與刪除

    首先我們改造一下request()方法,它需要完成兩個(gè)工作,一個(gè)就是在請(qǐng)求之前將url和取消請(qǐng)求方法push到我們前面定義的兩個(gè)屬性中,然后在請(qǐng)求完畢后(不管是失敗還是成功)都將其進(jìn)行刪除,實(shí)現(xiàn)代碼如下:

    // index.ts
    request<T>(config: RequestConfig): Promise<T> {
      return new Promise((resolve, reject) => {
        // 如果我們?yōu)閱蝹€(gè)請(qǐng)求設(shè)置攔截器,這里使用單個(gè)請(qǐng)求的攔截器
        if (config.interceptors?.requestInterceptors) {
          config = config.interceptors.requestInterceptors(config)
        }
        const url = config.url
        // url存在保存取消請(qǐng)求方法和當(dāng)前請(qǐng)求url
        if (url) {
          this.requestUrlList?.push(url)
          config.cancelToken = new axios.CancelToken(c => {
            this.cancelRequestSourceList?.push({
              [url]: c,
            })
          })
        }
        this.instance
          .request<any, T>(config)
          .then(res => {
            // 如果我們?yōu)閱蝹€(gè)響應(yīng)設(shè)置攔截器,這里使用單個(gè)響應(yīng)的攔截器
            if (config.interceptors?.responseInterceptors) {
              res = config.interceptors.responseInterceptors<T>(res)
            }
            resolve(res)
          })
          .catch((err: any) => {
            reject(err)
          })
          .finally(() => {
            url && this.delUrl(url)
          })
      })
    }

    這里我們將刪除操作進(jìn)行了抽離,將其封裝為一個(gè)私有方法,示例代碼如下:

    // index.ts
    /**
     * @description: 獲取指定 url 在 cancelRequestSourceList 中的索引
     * @param {string} url
     * @returns {number} 索引位置
     */
    private getSourceIndex(url: string): number {
      return this.cancelRequestSourceList?.findIndex(
        (item: CancelRequestSource) => {
          return Object.keys(item)[0] === url
        },
      ) as number
    }
    /**
     * @description: 刪除 requestUrlList 和 cancelRequestSourceList
     * @param {string} url
     * @returns {*}
     */
    private delUrl(url: string) {
      const urlIndex = this.requestUrlList?.findIndex(u => u === url)
      const sourceIndex = this.getSourceIndex(url)
      // 刪除url和cancel方法
      urlIndex !== -1 && this.requestUrlList?.splice(urlIndex as number, 1)
      sourceIndex !== -1 &&
        this.cancelRequestSourceList?.splice(sourceIndex as number, 1)
    }

    取消請(qǐng)求方法

    現(xiàn)在我們就可以封裝取消請(qǐng)求和取消全部請(qǐng)求了,我們先來封裝一下取消全部請(qǐng)求吧,這個(gè)比較簡單,只需要調(diào)用this.cancelRequestSourceList中的所有方法即可,實(shí)現(xiàn)代碼如下:

    // index.ts
    // 取消全部請(qǐng)求
    cancelAllRequest() {
      this.cancelRequestSourceList?.forEach(source => {
        const key = Object.keys(source)[0]
        source[key]()
      })
    }

    現(xiàn)在我們封裝一下取消請(qǐng)求,因?yàn)樗梢匀∠粋€(gè)和多個(gè),那它的參數(shù)就是url,或者包含多個(gè)URL的數(shù)組,然后根據(jù)傳值的不同去執(zhí)行不同的操作,實(shí)現(xiàn)代碼如下:

    // index.ts
    // 取消請(qǐng)求
    cancelRequest(url: string | string[]) {
      if (typeof url === 'string') {
        // 取消單個(gè)請(qǐng)求
        const sourceIndex = this.getSourceIndex(url)
        sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][url]()
      } else {
        // 存在多個(gè)需要取消請(qǐng)求的地址
        url.forEach(u => {
          const sourceIndex = this.getSourceIndex(u)
          sourceIndex >= 0 && this.cancelRequestSourceList?.[sourceIndex][u]()
        })
      }
    }

    測試

    測試請(qǐng)求方法

    現(xiàn)在我們就來測試一下這個(gè)請(qǐng)求方法,這里我們使用www.apishop.net/提供的免費(fèi)API進(jìn)行測試,測試代碼如下:

    <script setup lang="ts">
    // app.vue
    import request from './service'
    import { onMounted } from 'vue'
    interface Req {
      apiKey: string
      area?: string
      areaID?: string
    }
    interface Res {
      area: string
      areaCode: string
      areaid: string
      dayList: any[]
    }
    const get15DaysWeatherByArea = (data: Req) => {
      return request<Req, Res>({
        url: '/api/common/weather/get15DaysWeatherByArea',
        method: 'GET',
        data,
        interceptors: {
          requestInterceptors(res) {
            console.log('接口請(qǐng)求攔截')
            return res
          },
          responseInterceptors(result) {
            console.log('接口響應(yīng)攔截')
            return result
          },
        },
      })
    }
    onMounted(async () => {
      const res = await get15DaysWeatherByArea({
        apiKey: import.meta.env.VITE_APP_KEY,
        area: '北京市',
      })
      console.log(res.result.dayList)
    })
    </script>

    如果在實(shí)際開發(fā)中可以將這些代碼分別抽離。

    上面的代碼在命令中輸出

    接口請(qǐng)求攔截
    實(shí)例請(qǐng)求攔截器
    全局請(qǐng)求攔截器
    實(shí)例響應(yīng)攔截器
    全局響應(yīng)攔截器
    接口響應(yīng)攔截
    [{&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}, {&hellip;}]

    測試取消請(qǐng)求

    首先我們?cè)?code>.server/index.ts中對(duì)取消請(qǐng)求方法進(jìn)行導(dǎo)出,實(shí)現(xiàn)代碼如下:

    // 取消請(qǐng)求
    export const cancelRequest = (url: string | string[]) => {
      return request.cancelRequest(url)
    }
    // 取消全部請(qǐng)求
    export const cancelAllRequest = () => {
      return request.cancelAllRequest()
    }

    然后我們?cè)?code>app.vue中對(duì)其進(jìn)行引用,實(shí)現(xiàn)代碼如下:

    <template>
      <el-button
        @click="cancelRequest('/api/common/weather/get15DaysWeatherByArea')"
        >取消請(qǐng)求</el-button
      >
      <el-button @click="cancelAllRequest">取消全部請(qǐng)求</el-button>
      <router-view></router-view>
    </template>
    <script setup lang="ts">
    import request, { cancelRequest, cancelAllRequest } from './service'
    </script>

    發(fā)送請(qǐng)求后,點(diǎn)擊按鈕即可實(shí)現(xiàn)對(duì)應(yīng)的功能

    讀到這里,這篇“如何使用Typescript封裝axios”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI