All files / src/export exportExcel.ts

20.69% Statements 6/29
0% Branches 0/14
0% Functions 0/4
17.86% Lines 5/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 621x 1x   1x                             1x                       1x                                                              
import * as R from 'ramda';
import { getEnv } from '../biz/getEnv';
 
const addQueries = (params: {
  [x: string]: any;
  token?: string | null;
}) => {
  const arr: string[] = [];
  Object.keys(params).forEach((key) => {
    if (!(R.isEmpty(params[key]) || R.isNil(params[key]))) {
      arr.push(`${key}=${params[key]}`);
    }
  });
  return arr.join("&");
};
 
type ENV_PREFIX = 'prod' | 'dev' | 'test';
 
const CENV: Record<ENV_PREFIX, string> = {
  'prod': 'https://gateway.ywwl.com',
  'dev': 'https://dev-gateway.ywwl.com',
  'test': 'https://test-gateway.ywwl.com'
}
 
/**
 * 
 * @param url 下载地址
 * @param params 参数集合
 * @param isPrefix = false 默认不带前缀,即是否带域名
 */
export const exportExcel = (url: string, params = {}, isPrefix = false) => {
  const env = getEnv() as ENV_PREFIX;
  let token: string | null;
  if (typeof window !== 'undefined') {
    token = window.localStorage.getItem("token");
  }
 
  const data = Object.assign({}, params, {
    //@ts-ignore
    token: token,
  });
 
  if (!/^https.*/.test(url)) {
    url = url.replace('http', 'https');
  }
 
  const downloadUrl = `${!isPrefix ? url : CENV[env]}${url}?${addQueries(data)}`;
  console.log('YWFE下载地址=>', downloadUrl);
  const id = `alink_${new Date().getTime()}`;
  const aDom = document.createElement("a");
  aDom.setAttribute("href", downloadUrl);
  aDom.setAttribute("target", "_blank");
  aDom.setAttribute("id", id);
  if (!document.getElementById(id)) {
    document.body.appendChild(aDom);
  }
  aDom.click();
  setTimeout(() => {
    document.body.removeChild(aDom);
  }, 0);
};