ClassyGitdnevend
← dnevend 的 Gist

axios

code1 个文件约 2 分钟创建于 2024-10-18在 GitHub 打开 ↗

axios.ts

import axios from "axios";
import type { HttpErrorResponse, HttpResponse } from "./type";
import type {
    InternalAxiosRequestConfig,
    AxiosRequestConfig,
    AxiosResponse,
    AxiosInstance,
    AxiosError
} from 'axios'
import { storageGet } from "../storage";
import toast from "react-hot-toast";

export class Http {

    instance: AxiosInstance

    baseConfig: AxiosRequestConfig = {
        baseURL: 'https://xxx.com/api',
        headers: { 'Content-Type': 'application/json' }
    }

    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(Object.assign(this.baseConfig, config))

        this.instance.interceptors.request.use(
            async (config: InternalAxiosRequestConfig) => {

                if (storageGet('token')) {
                    config.headers['Authorization'] = storageGet('token')
                }

                return config
            },
            (error: AxiosError) => {
                return Promise.reject(error)
            }
        )

        this.instance.interceptors.response.use(
            (response: AxiosResponse<HttpResponse>) => {
                const { code, msg } = response.data

                if (code !== 200) {
                    toast.error(msg)
                    return Promise.reject(response)
                }

                return response
            },
            (error: AxiosError<HttpErrorResponse>) => {

                if (error.response?.data.msg) {
                    toast.error(error.response.data.msg)
                }

                return Promise.reject(error.response)
            }
        )

        this.instance.interceptors.response.use(
            (response: AxiosResponse<HttpResponse>) => {
                return { ...response, ...response.data }
            }
        )
    }

    public get<T = any>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<HttpResponse<T>> {
        return this.instance.get(url, config)
    }

    public post<T = any>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<HttpResponse<T>> {
        return this.instance.post(url, data, config)
    }

    public put<T = any>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<HttpResponse<T>> {
        return this.instance.put(url, data, config)
    }

    public patch<T = any>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<HttpResponse<T>> {
        return this.instance.patch(url, data, config)
    }

    public delete<T = any>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<HttpResponse<T>> {
        return this.instance.delete(url, config)
    }
}

export default new Http({ timeout: 30000 })