import { AxiosInstance } from "axios";

export default function (axios: AxiosInstance, regexes: [RegExp] | []) {
  // cachingGet
  const cache = new Map();

  return function cachedGet(url: string) {
    const key = url;

    if (regexes.some((regex) => url.match(regex))) {
      if (cache.has(key)) {
        const request = cache.get(key);
        // console.log("cache.get(key):" + request.then(v => console.log(v)));
        return request;
      } else {
        // @ts-ignore
        const request = axios.get(...arguments);
        return request.then((v) => {
          if (v.status === 200) {
            // 如果能取到数据，才缓存
            cache.set(key, request);
          }
          return request;
        });
      }
    } else {
      // @ts-ignore
      const request = axios.get(...arguments);
      return request;
    }
  };
}
