import axios from 'axios';

import type { GetFileFromUrl } from './types';

/**
 * 请求返回文件
 * @description 注意不用 window.fetch，vConsole 对 window.fetch 做了劫持重写导致无法请求文件成功
 * @param {string} url 在线文件地址
 * @param {string} [filename=''] 自定义文件名，默认取链接名称
 * @returns <File|Null>
 */
const getFileFromUrl: GetFileFromUrl = async (url: string, filename?: string) => {
  const name = filename || url.split('/').pop() || 'sucai.pag';
  const response = await axios({
    method: 'get',
    url,
    responseType: 'blob',
  });

  const { data } = response;
  if (data) {
    return new File([data], name, {
      type: data.type,
    });
  }

  return null;
};

export {
  getFileFromUrl,
};
