Xi-Yuer

Xi-Yuer

github

AxiosRequest

基于 Axios 封装一个通用请求#

Type.d.ts#

// type
import type {
    AxiosRequestConfig,
    InternalAxiosRequestConfig,
    AxiosInterceptorOptions,
    AxiosResponse,
} from 'axios'

// 扩展拦截器
export interface RequestConfig extends AxiosRequestConfig {
    requestInterceptor?: {
        onFulfilled?: (
            value: InternalAxiosRequestConfig,
        ) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>
        onRejected?: ((error: any) => any) | null
        options?: AxiosInterceptorOptions
    }

    responseInterceptor?: {
        onFulfilled?: (value: AxiosResponse) => AxiosResponse
        onRejected?: ((error: any) => any) | null
        options?: AxiosInterceptorOptions
    }
}

export type InterceptorType = Partial<
    Pick<RequestConfig, 'requestInterceptor' | 'responseInterceptor'>
>

export interface IResponse<T = any> {
    data: T
    message: string
    statusCode: number
    timestamp: Date
}

请求类#

// request
import axios, {
    type AxiosInstance,
    type AxiosResponse,
    type CancelTokenSource,
} from 'axios'
import type { IResponse, InterceptorType, RequestConfig } from './type'

class Request {
    Instance: AxiosInstance | null
    constructor(
        // 实例的请求基础路径
        private readonly baseURL: string,
        // 实例的请求超时时间
        private readonly timeOUT: number,
        // 实例的拦截器
        private readonly interceptor?: InterceptorType,
        // 取消令牌
        private cancelTokenSource: CancelTokenSource | null = null,
    ) {
        // 创建一个实例
        this.Instance = axios.create({
            baseURL: this.baseURL,
            timeout: this.timeOUT,
        })
        // 配置实例的请求拦截
        if (this.interceptor?.requestInterceptor) {
            this.Instance.interceptors.request.use(
                this.interceptor.requestInterceptor.onFulfilled,
                this.interceptor.requestInterceptor.onRejected,
                this.interceptor.requestInterceptor.options,
            )
        }
        // 配置实例的响应拦截
        if (this.interceptor?.responseInterceptor) {
            this.Instance.interceptors.response.use(
                this.interceptor.responseInterceptor.onFulfilled,
                this.interceptor.responseInterceptor.onRejected,
                this.interceptor.responseInterceptor.options,
            )
        }
    }
    // 实例方法 request
    public request<T = AxiosResponse<any>>(config: RequestConfig): Promise<T> {
        return new Promise<T>((resolve, reject) => {
            // 单个接口的请求拦截
            if (config.requestInterceptor) {
                this.Instance?.interceptors.request.use(
                    config.requestInterceptor.onFulfilled,
                    config.requestInterceptor.onRejected,
                    config.requestInterceptor.options,
                )
            }
            // 单个接口的响应拦截
            if (config.responseInterceptor) {
                this.Instance?.interceptors.response.use(
                    config.responseInterceptor.onFulfilled,
                    config.responseInterceptor.onRejected,
                    config.responseInterceptor.options,
                )
            }

            this.cancelTokenSource = axios.CancelToken.source()
            this.Instance?.request<T>({
                ...config,
                cancelToken: this.cancelTokenSource.token,
            })
                .then((res) => {
                    resolve(res as any)
                })
                .catch((err) => {
                    reject(err)
                })
        })
    }

    // 取消请求
    public cancelRequest(): void {
        if (this.cancelTokenSource) {
            this.cancelTokenSource.cancel('取消请求')
        }
    }

    public get<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'GET', ...config })
    }
    public post<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'POST', ...config })
    }
    public delete<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'DELETE', ...config })
    }
    public patch<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'PATCH', ...config })
    }
    public put<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'PUT', ...config })
    }
    public head<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'HEAD', ...config })
    }
    public options<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'OPTIONS', ...config })
    }
    public trace<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'TRACE', ...config })
    }
    public connect<T = any>(config: RequestConfig) {
        return this.request<T>({ method: 'CONNECT', ...config })
    }
}

使用方式#

/**
 *
 * ================================================================================
 * ===================================测试代码=====================================
 * ================================================================================
 *
 */
const instance = new Request('https://xiyuer.club/api/v1', 10000, {
    requestInterceptor: {
        onFulfilled(config) {
            console.log('实例请求成功拦截')
            return config
        },
        onRejected(error) {
            console.log('实例请求失败拦截')
            return error
        },
    },
    responseInterceptor: {
        onFulfilled(value) {
            console.log('实例响应成功拦截')
            return value.data
        },
        onRejected(error) {
            console.log('实例响应失败拦截')
            return error
        },
    },
})

type IData = any[]

const getBanner = () => {
    instance
        .get<IResponse<IData>>({
            url: '/banner',
            requestInterceptor: {
                onFulfilled(config) {
                    console.log('接口请求成功拦截')
                    return config
                },
                onRejected(err) {
                    console.log('接口请求失败拦截')
                    return err
                },
            },
            responseInterceptor: {
                onFulfilled(data) {
                    console.log('接口响应成功拦截')
                    return data
                },
                onRejected(err) {
                    console.log('接口响应失败拦截')
                    return err
                },
            },
        })
        .then((res) => {
            console.log(res)
        })
}
getBanner()
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。