Xi-Yuer

Xi-Yuer

github

AxiosRequest

A General Request Encapsulated Based on Axios#

Type.d.ts#

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

// Extend interceptor
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 Class#

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

class Request {
    Instance: AxiosInstance | null
    constructor(
        // Base path for instance requests
        private readonly baseURL: string,
        // Timeout for instance requests
        private readonly timeOUT: number,
        // Instance interceptors
        private readonly interceptor?: InterceptorType,
        // Cancel token
        private cancelTokenSource: CancelTokenSource | null = null,
    ) {
        // Create an instance
        this.Instance = axios.create({
            baseURL: this.baseURL,
            timeout: this.timeOUT,
        })
        // Configure request interception for the instance
        if (this.interceptor?.requestInterceptor) {
            this.Instance.interceptors.request.use(
                this.interceptor.requestInterceptor.onFulfilled,
                this.interceptor.requestInterceptor.onRejected,
                this.interceptor.requestInterceptor.options,
            )
        }
        // Configure response interception for the instance
        if (this.interceptor?.responseInterceptor) {
            this.Instance.interceptors.response.use(
                this.interceptor.responseInterceptor.onFulfilled,
                this.interceptor.responseInterceptor.onRejected,
                this.interceptor.responseInterceptor.options,
            )
        }
    }
    // Instance method request
    public request<T = AxiosResponse<any>>(config: RequestConfig): Promise<T> {
        return new Promise<T>((resolve, reject) => {
            // Request interception for a single interface
            if (config.requestInterceptor) {
                this.Instance?.interceptors.request.use(
                    config.requestInterceptor.onFulfilled,
                    config.requestInterceptor.onRejected,
                    config.requestInterceptor.options,
                )
            }
            // Response interception for a single interface
            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)
                })
        })
    }

    // Cancel request
    public cancelRequest(): void {
        if (this.cancelTokenSource) {
            this.cancelTokenSource.cancel('Cancel request')
        }
    }

    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 })
    }
}

Usage#

/**
 *
 * ================================================================================
 * ===================================Test Code=====================================
 * ================================================================================
 *
 */
const instance = new Request('https://xiyuer.club/api/v1', 10000, {
    requestInterceptor: {
        onFulfilled(config) {
            console.log('Instance request successfully intercepted')
            return config
        },
        onRejected(error) {
            console.log('Instance request failed interception')
            return error
        },
    },
    responseInterceptor: {
        onFulfilled(value) {
            console.log('Instance response successfully intercepted')
            return value.data
        },
        onRejected(error) {
            console.log('Instance response failed interception')
            return error
        },
    },
})

type IData = any[]

const getBanner = () => {
    instance
        .get<IResponse<IData>>({
            url: '/banner',
            requestInterceptor: {
                onFulfilled(config) {
                    console.log('Interface request successfully intercepted')
                    return config
                },
                onRejected(err) {
                    console.log('Interface request failed interception')
                    return err
                },
            },
            responseInterceptor: {
                onFulfilled(data) {
                    console.log('Interface response successfully intercepted')
                    return data
                },
                onRejected(err) {
                    console.log('Interface response failed interception')
                    return err
                },
            },
        })
        .then((res) => {
            console.log(res)
        })
}
getBanner()
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.