import axios, { AxiosRequestConfig } from "axios";
const config: RequestConfig = {
  timeout: 10000,
  headers: { "Content-Type": "application/json; charset=utf-8" },
};

export type RequestConfig = AxiosRequestConfig & {
  interceptors?: any;
};

export function createRequest(defReqConfig: RequestConfig) {
  const { interceptors, ...httpConfig } = defReqConfig;
  const http = axios.create({ ...config, ...httpConfig });
  Object.values(interceptors || {})?.forEach((item: any) => {
    item.request && http.interceptors.request.use(item.request);
    item.response && http.interceptors.response.use(item.response);
  });
  return async function (url: string, config: AxiosRequestConfig) {
    const thisConfig = Object.assign({}, config, { url });

    try {
      let response = (await http(thisConfig)).data;
      return response;
    } catch (error) {
      throw console.error({ msg: `${error}`, result: error });
    }
  };
}
