ts封装axios

type Method = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'DELETE';
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json';
interface AxiosRequest {
    baseUrl?: string;
    url: string;
    data?: any;
    param?: any;
    method: Method;
    headers?: any;
    timeout?: number;
    responseType: ResponseType;
}
interface CustomResponse {
    readonly status: number;
    message?: string;
    data?: any;
}
interface Pending {
    url: string;
    message: string;
    param?: any;
    data?: any;
    cancel: Function;
}
import axios, { AxiosRequestConfig } from 'axios';

const instance = axios.create({
    timeout: 10000,
    responseType: 'json'
})

const pending: Array<PendingType> = [];
const cancelToken = axios.CancelToken;

const removePending = (config:AxiosRequestConfig) => {

}

instance.interceptors.request.use((request:any)=>{
    removePending(request);
    request.cancelToken = new cancelToken((c) => {
        pending.push({
            url:request.url,
            method:request.method,
            param:request.param,
            data:request.data,
            cancel:request.cancel
        })
    })
})

instance.interceptors.reponse.use(()=>{

})


class BaseHttp {
    baseUrl: string = ProcessingInstruction.env.VUE_APP_BaseURL as string;
    headers: object = {
        ContentType: 'application/json; charset=utf-8'
    }
    private ApiAxios({
        baseUrl = this.baseUrl,
        url,
        data,
        param,
        method,
        headers,
        timeout,
    }: AxiosRequest): Promise<CustomResponse> {
        return new Promise((resolve, reject) => {
            instance({
                baseUrl,
                url,
                data,
                param,
                method,
                headers,
            }).then((res: any) => {
                if (res.status === 200) {
                    //TODO:正常返回
                    resolve(res.data);
                } else {
                    resolve({
                        status: 500,
                        message: res.error.message || '',
                    })
                }
            })
        })
    }

    public getReq({
        baseUrl,
        url,
        data,
        param,
        method,
        headers,
    }: AxiosRequest) {
        return this.ApiAxios({
            baseUrl,
            url,
            data,
            param,
            method: 'GET',
            headers,
        })
    }
}

new BaseHttp().getReq();
posted on 2022-02-08 17:37  Liillian  阅读(361)  评论(0)    收藏  举报