api(样板)文件

/* eslint-disable @typescript-eslint/restrict-plus-operands */
/* eslint-disable no-loop-func */
/**
 * @file api
 */
import axios, {AxiosRequestConfig} from 'axios';
import {message} from 'antd';
import {getToken} from '@/utils';
import {getUUID} from '@/utils/uuid';
import {isTkylProd} from '@/utils/env';

type CreateAPI<T> = (config: T) => Record<keyof T, (data?: any, options?: AxiosRequestConfig) => Promise<any>>;
export const commonService = process.env.NODE_ENV === 'development' ? '/ml' : '/gateway';
const apiConfig = {
    // tk登陆url
    getRedirectUrl: '/rbac-sys/taikang/url',
    // 获取当前登录用户信息
    getUserinfo: {
        url: '/rbac-sys/auth/info',
        method: 'GET'
    },
    // 获取管理员标签列表,
    getLabelListAdmin: {
        url: '/insight/label/labelListAdmin',
        method: 'GET'
    },
    // 自定义画像标签列表,
    getLabeListPortion: {
        url: '/insight/label/labelListPortion',
        method: 'GET'
    },
    // 获取类目信息,
    getClassList: {
        url: '/insight/label/classList',
        method: 'GET'
    },
    // 创建类目
    classCreate: {
        url: '/insight/label/classCreate',
        method: 'POST'
    },
    // 删除类目
    classDelete: {
        url: '/insight/label/classDelete',
        method: 'GET'
    }
    ...
}

export const getApiConfig = <T extends keyof typeof apiConfig>(key: T) => {
    const result = apiConfig[key];
    if (typeof result === 'string') {
        return '/gateway' + result;
    }
    return '/gateway' + result.url;
};

export function goLogin() {
    if (isTkylProd) {
        window.location.href = getApiConfig('getRedirectUrl');
    } else {
        window.location.href = window.routerBase + `/login`;
    }
}

const createApi: CreateAPI<typeof apiConfig> = (config: typeof apiConfig) => {
    const apiFuncs: any = {};
    const keys = Object.keys(config) as Array<keyof typeof apiConfig>;
    for (const k of keys) {
        apiFuncs[k] = (data?: any, options?: AxiosRequestConfig) => {
            let requestOptions: AxiosRequestConfig = {};
            const apiOption = config[k] as string | AxiosRequestConfig;
            if (typeof apiOption === 'string') {
                requestOptions = {
                    url: apiOption,
                    method: 'POST'
                };
            } else {
                requestOptions = {
                    ...apiOption,
                    url: apiOption.url,
                    ...options
                } as Partial<AxiosRequestConfig>;
            }

            if (requestOptions.method?.toLowerCase() === 'get' || requestOptions.method?.toLowerCase() === 'delete') {
                requestOptions.params = {
                    ...data,
                    // GET 请求添加随机参数避免cache
                    t: Date.now()
                };
            } else {
                requestOptions.data = data;
            }
            return new Promise((resolve, reject) => {
                axios(requestOptions)
                    .then((res) => {
                        if (res?.config.responseType === 'blob' && res) {
                            resolve(res);
                        }
                        if (res.status === 200 && (res.data?.ret === '0' || res.data?.ret === 'SUCCESS')) {
                            resolve(res.data.content);
                        } else if (res.status === 200 && res.data?.code === 'CMN000000') {
                            resolve(res.data.data);
                        } else if (res.data?.ret === 'NO_LOGIN') {
                            goLogin();
                        } else if (res.data) {
                            reject(res.data);
                        } else {
                            reject(res);
                        }
                    })
                    .catch((e) => {
                        if (e.response && e.response?.status >= 500) {
                            message.destroy();
                            message.error('服务器异常');
                        }
                        // TODO: global error handle
                        reject(e);
                    });
            });
        };
    }
    // 增加拦截器
    axios.interceptors.request.use((config) => {
        config.url = commonService + config.url;
        return config;
    });
    // token注入
    axios.interceptors.request.use((config) => {
        config.headers = {
            Authorization: getToken()
        };
        if (config.url?.includes('/insight/label/import/excel')) {
            config.headers.UUID = getUUID();
        }
        return config;
    });
    // 返回拦截
    axios.interceptors.response.use(
        (res) => {
            // console.log(res)
            return res;
        },
        (err) => {
            if (err?.response?.status === 401) {
                goLogin();
                return;
            }
            return Promise.reject(err);
        }
    );
    return apiFuncs;
};
const api = createApi(apiConfig);
// custom some api func here eg: api.getUserInfo = () => {};

export default api;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒枫落林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值