axios 封装请求

101 阅读1分钟
import { uiTools } from '@/components/ui';
import { dtLogger } from '@ali/dt-jssdk/common/logger';
import axios, { AxiosResponse } from 'axios';
import { getGlobalProps } from '../utils';

/**
 * 获取全局配置
 */
export function getGlobalProps(key: string) {
  // @ts-ignore
  return (window.g_config || window.pageConfig || {})[key] || '';
}

interface HttpClientConfig {
  logger: boolean;
}

const DEFAULT_CLIENT_CONFIG: HttpClientConfig = {
  logger: true,
};

/**
 * 通用错误处理函数
 */
function handleError(e: any) {
  let _e: AxiosResponse = e;
  if (e.response) {
    _e = e.response;
  }
  const _data = _e?.data || {};
  const errMsg = _data.message || _data.errMsg || _data.errorMsg || '';
  uiTools.message.error(errMsg ? `接口请求失败:${errMsg}` : '接口请求失败,请打开控制台查看网络请求');
  throw _e;
}

/**
 * http客户端
 */
// @Singleton()
export class HttpClient {
  private config: HttpClientConfig = { ...DEFAULT_CLIENT_CONFIG };

  private axiosInstance;

  constructor(config: Partial<HttpClientConfig> = {}) {
    const loginInNewWindow = localStorage.getItem('loginInNewWindow');
    if (getGlobalProps('_csrf_token') && loginInNewWindow === 'yes') {
      window.close();
      localStorage.removeItem('loginInNewWindow');
    }
    this.setConfig(config);
    this.axiosInstance = axios.create({
      baseURL: location.origin,
      headers: {
        'x-xsrf-token': getGlobalProps('_csrf_token'),
        'x-requested-with': 'XMLHttpRequest',
      },
    });
  }

  async get<T = any>(url: string, data = {}): Promise<T> {
    return this.axiosInstance.get(url, { params: this.addGlobalParam(data) }).then((res) => {
      this.log(`[HTTP][GET] ${url}`, res);
      if (res.status === 200 && res.data.success) {
        const content = (res.data as any)?.content;
        return content !== undefined ? content : res.data;
      } else {
        throw res;
      }
    }).catch(handleError);
  }

  async post<T = any>(url: string, data = {}): Promise<T> {
    return this.axiosInstance.post(url, this.addGlobalParam(data)).then((res) => {
      this.log(`[HTTP][POST] + ${url}`, res);
      if (res.status === 200 && res.data.success) {
        const content = (res.data as any)?.content;
        return content !== undefined ? content : res.data;
      } else {
        throw res;
      }
    }).catch(handleError);
  }

  async put<T = any>(url: string, data = {}) {
    // TODO
    throw new Error();
  }

  async delete(url: string, data = {}) {
    // TODO
    throw new Error();
  }

  /**
   * 初始化配置
   * @param config
   */
  setConfig(config: Partial<HttpClientConfig>) {
    this.config = Object.assign(this.config, config);
  }

  /**
   * 设置拦截器
   * @param onFulfilled 成功方法
   * @param onRejected 失败方法
   * @returns 拦截器id,用于eject
   */
  setResponseInterceptor<T = any, V = any>(
    onFulfilled?: (value: AxiosResponse<V>) => T | Promise<T>,
    onRejected?: (error: any) => any,
  ) {
    return this.axiosInstance.interceptors.response.use(onFulfilled, onRejected);
  }

  /**
   * 消除拦截器
   * @param handler 注册的拦截器id
   */
  ejectResponseInterceptor(handler: number) {
    return this.axiosInstance.interceptors.response.eject(handler);
  }

  /**
   * 简单日志打印
   * @param msg
   */
  private log(title: string, ...msg: any[]) {
    if (this.config.logger) {
      dtLogger.log(title, ...msg);
    }
  }

  private addGlobalParam(data: any) {
    return {
      ...data,
      _csrf: getGlobalProps('_csrf_token'),
    };
  }
}

export const httpClient: HttpClient = new HttpClient();

get post 请求

import { httpClient } from '@/infrastructure/http';

// get 请求
interface IGetListRes {}
export function getList(id: string, nextIndex?: number): Promise<IGetListRes> {
  return httpClient.get('/api/get/list.json', { operateId: id, moreThan: nextIndex });
}

interface IGetLogParams {}
interface IGetLogRes {}
export function getLog(params: IGetLogParams): Promise<IGetLogRes> {
  return httpClient.get('/api/get/log.json', params);
}


// post 请求
interface IPostChangeParams {}
export function postChange(params: IPostChangeParams): Promise<void> {
  return httpClient.post('/api/post/change.json', params);
}