ts + axios 简单封装

index.ts

/**
 * @Author: boyyang
 * @Date: 2022-04-16 11:45:46
 * @LastEditTime: 2022-04-17 15:58:22
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \drawingBed\src\utils\http\index.ts
 * @[如果痛恨所处的黑暗,请你成为你想要的光。 --塞尔维亚的天空]
 */

import { Axios } from './http'
import { transForm } from './transform'
import { env } from '@/utils/env'

const createHttp = () => {
    return new Axios({
        baseURL: env.VITE_APP_API_URL,
        timeout: 10 * 1000,
        transForm: transForm,
        // 配置项,下面的选项都可以在独立的接口请求中覆盖
        requestOptions: {
            // 是否返回原生响应头 比如:需要获取响应头时使用该属性
            isReturnNativeResponse: false,
            // 需要对返回数据进行处理
            isTransformResponse: true,
            // get请求添加时间戳
            joinTime: true,
            // 是否携带token
            withToken: true,
            // 显示请求后message
            isShowMessage: true,
            // 显示请求成功message
            isShowSuccessMessage: true,
            // 显示请求失败message
            isShowErrorMessage: true,
            // 序列化请求参数 post formData
            serializeParams: true
        },
    })
}

const http = createHttp()

export {
    http
}

http.ts

/**
 * @Author: boyyang
 * @Date: 2022-04-16 11:29:46
 * @LastEditTime: 2022-04-17 17:50:55
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \drawingBed\src\utils\http\http.ts
 * @[如果痛恨所处的黑暗,请你成为你想要的光。 --塞尔维亚的天空]
 */

import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { AxiosOptions, RequestOptions, Result } from './types'

class Axios {
    private axiosInstance: AxiosInstance
    private options: AxiosOptions
    constructor(options: AxiosOptions) {
        this.options = options
        this.axiosInstance = axios.create(options)
        this.setupInterceptors()
    }
    // 初始化拦截器
    private setupInterceptors() {
        const { requestInterceptorsCatch } = this.getTransForm() || {}
        // 请求之前的拦截器
        this.axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
            const { requestInterceptors } = this.getTransForm() || {}
            if (requestInterceptors) {
                config = requestInterceptors(config, this.options)
            }
            return config
        },
            (error: any) => {
                return Promise.reject(error)
            }
        )
        // 请求之后的拦截器
        this.axiosInstance.interceptors.response.use((response: AxiosResponse<any>) => {
            console.log(response)
            const { responseInterceptors } = this.getTransForm() || {}
            if (responseInterceptors) {
                response = responseInterceptors(response)
            }
            return response
        },
            (error: any) => {
                return Promise.reject(error)
            }
        )
    }
    // 请求
    public request<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<Result | T> {
        const transForm = this.getTransForm()
        const { beforeRequestHook } = transForm || {}
        const { requestOptions } = this.options || {}
        const opt: RequestOptions = Object.assign({}, requestOptions, options)
        if (beforeRequestHook) {
            config = beforeRequestHook(config, opt)
        }
        return new Promise((resolve, reject) => {
            this.axiosInstance
                .request<any, AxiosResponse<Result>>(config)
                .then((response: AxiosResponse<Result>) => {
                    const { transformRequestData } = this.getTransForm() || {}
                    if (transformRequestData) {
                        try {
                            const res = transformRequestData(response, opt)
                            resolve(res)
                        } catch (err) {
                            reject(err || new Error('request error!'))
                        }
                        return
                    }
                    resolve(response as unknown as Promise<T>)
                })
                .catch((error: any) => {
                    const { requestCatch } = this.getTransForm() || {}
                    if (requestCatch) {
                        requestCatch(error)
                    }
                    reject(error)
                })
        })
    }
    // 获取转换器
    private getTransForm() {
        const { transForm } = this.options
        return transForm
    }
}

export {
    Axios
}

transForm.ts

/**
 * @Author: boyyang
 * @Date: 2022-04-17 11:51:40
 * @LastEditTime: 2022-04-17 17:59:50
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \drawingBed\src\utils\http\transform.ts
 * @[如果痛恨所处的黑暗,请你成为你想要的光。 --塞尔维亚的天空]
 */

import { TransForm, RequestOptions, Result, AxiosOptions } from './types'
import { AxiosResponse, AxiosRequestConfig } from 'axios'
import qs from 'qs'
import { useUserStoreWithOut } from '@/store/modules/user'

const userStore = useUserStoreWithOut()

const transForm: TransForm = {
    // 请求前hook
    beforeRequestHook: (config: AxiosRequestConfig, options: RequestOptions) => {
        const { serializeParams, joinTime, withToken } = options
        if (serializeParams) { // 序列化参数
            if (config.method?.toUpperCase() === 'GET') {
                if (joinTime) { // 是否拼接时间戳
                    config.params = {
                        ...config.params,
                        _t: Date.now()
                    }
                }
            } else {
                config.data = qs.stringify(config.data)
            }
        }
        if (withToken) {    // 如果需要带上token
            config.headers = {
                ...config.headers,
                token: userStore.getToken
            }
        }
        return config
    },
    // 转换请求数据
    transformRequestData: (res: AxiosResponse<Result>, options: RequestOptions) => {
        const {
            isShowMessage,
            isShowSuccessMessage,
            isShowErrorMessage,
            isReturnNativeResponse,
            isTransformResponse
        } = options
        const { data, config } = res
        const { code, msg } = data
        // 是否显示请求成功信息
        if (isShowMessage) {
            if (isShowSuccessMessage) {
                if (code === 1 && msg && config.method?.toUpperCase() === 'POST') {
                    // 成功
                    window.$message.success(msg)
                }
            }
            if (isShowErrorMessage) {
                if (code === 0 && msg) {
                    // 失败
                    window.$message.error(msg)
                }
            }
        }
        // 是否返回原生响应头
        if (isReturnNativeResponse) {
            return res
        }
        // 是否进行任何处理,直接返回
        if (isTransformResponse) {
            return data
        }
    },
    // 请求拦截器
    requestInterceptors: (config: AxiosRequestConfig, options: AxiosOptions): AxiosRequestConfig => {
        return config
    },
    // 响应拦截器
    responseInterceptors: (res: AxiosResponse<any>): AxiosResponse<any> => {
        return res
    },
    responseInterceptorsCatch: (error: Error) => {
        console.log(error)
    },
    requestCatch: (error: any) => {
        console.log(error.response)
        const { msg } = error.response.data
        window.$message.error(msg)
        return error
    }
}

export {
    transForm
}

types.ts

/**
 * @Author: boyyang
 * @Date: 2022-04-17 11:32:55
 * @LastEditTime: 2022-04-17 17:52:38
 * @LastEditors: boyyang
 * @Description: 
 * @FilePath: \drawingBed\src\utils\http\types.ts
 * @[如果痛恨所处的黑暗,请你成为你想要的光。 --塞尔维亚的天空]
 */

import type { AxiosRequestConfig, AxiosResponse } from 'axios'

export interface AxiosOptions extends AxiosRequestConfig {
    requestOptions?: RequestOptions,
    transForm?: TransForm
}

export interface RequestOptions {
    // 序列化请求参数
    serializeParams?: boolean
    // 是否显示提示信息
    isShowMessage?: boolean
    // 是否解析成JSON
    isParseToJson?: boolean
    // 成功的文本信息
    successMessageText?: string
    // 是否显示成功信息
    isShowSuccessMessage?: boolean
    // 是否显示失败信息
    isShowErrorMessage?: boolean
    // 是否添加时间戳
    joinTime?: boolean
    // 不进行任何处理,直接返回
    isTransformResponse?: boolean
    // 是否返回原生响应头
    isReturnNativeResponse?: boolean
    // 是否携带token
    withToken?: boolean
}

export interface Result<T = any> {
    code: number
    msg: string
    data: T
}

export abstract class TransForm {
    /**
    * @description: 请求之前处理配置
    * @description: Process configuration before request
    */
    beforeRequestHook?: (config: AxiosRequestConfig, options: RequestOptions) => AxiosRequestConfig

    /**
     * @description: 请求成功处理
     */
    transformRequestData?: (res: AxiosResponse<Result>, options: RequestOptions) => any

    /**
     * @description: 请求失败处理
     */
    requestCatch?: (e: any) => Promise<any>

    /**
     * @description: 请求之前的拦截器
     */
    requestInterceptors?: (config: AxiosRequestConfig, options: AxiosOptions) => AxiosRequestConfig

    /**
     * @description: 请求之后的拦截器
     */
    responseInterceptors?: (res: AxiosResponse<any>) => AxiosResponse<any>

    /**
     * @description: 请求之前的拦截器错误处理
     */
    requestInterceptorsCatch?: (error: Error) => void

    /**
     * @description: 请求之后的拦截器错误处理
     */
    responseInterceptorsCatch?: (error: Error) => void
}

posted @ 2022-04-19 21:11  boyyang  阅读(977)  评论(0编辑  收藏  举报
//黑猫咪:https://unpkg.com/live2d-widget-model-hijiki@1.0.5/assets/hijiki.model.json //白猫咪:https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json //萌娘:https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json //狗狗:https://unpkg.com/live2d-widget-model-wanko@1.0.5/assets/wanko.model.json //萌妹1号:https://unpkg.com/live2d-widget-model-z16@1.0.5/assets/z16.model.json //萌妹2号:https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json //萌妹3号:https://unpkg.com/live2d-widget-model-hibiki@1.0.5/assets/hibiki.model.json //妹子4号:https://unpkg.com/live2d-widget-model-izumi@1.0.5/assets/izumi.model.json //妹子5号:https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json //6号:https://unpkg.com/live2d-widget-model-nico@1.0.5/assets/nico.model.json //7号:https://unpkg.com/live2d-widget-model-ni-j@1.0.5/assets/ni-j.model.json //8号:https://unpkg.com/live2d-widget-model-nipsilon@1.0.5/assets/nipsilon.model.json //9号:https://unpkg.com/live2d-widget-model-nito@1.0.5/assets/nito.model.json //10号:https://unpkg.com/live2d-widget-model-tsumiki@1.0.5/assets/tsumiki.model.json //11号:https://unpkg.com/live2d-widget-model-unitychan@1.0.5/assets/unitychan.model.json //帅哥1号:https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json //帅哥2号:https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json