All files / io loadSdk.ts

94.73% Statements 18/19
100% Branches 0/0
100% Functions 2/2
94.73% Lines 18/19

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 62 63 64 65 66 67 68 69 70 71 72 73 74                                  1x 1x 1x                       1x   1x         1x   1x 1x       1x 2x                     6x   2x   1x     1x   1x 1x   1x     1x  
/**
 * sdk 加载统一封装
 * - 多次调用不会发起重复请求
 * @method loadSdk
 * @param {Object} options 选项
 * @param {String} options.name sdk 全局变量名称
 * @param {String} options.url script 地址
 * @param {String} [options.charset=''] script 编码
 * @return {Promise<unknown>} sdk 加载完成,回调加载的对象
 * @example
 * import { loadSdk } from '@spore-ui/tskit';
 * loadSdk({
 *   name: 'TencentCaptcha',
 *   url: 'https://ssl.captcha.qq.com/TCaptcha.js'
 * }).then(TencentCaptcha => {})
 */
 
import get from 'lodash/get';
import set from 'lodash/set';
import { getScript } from './getScript';
 
export interface TypeLoadSdkOptions {
  name: string;
  url: string;
  charset?: string;
}
 
export interface TypePromiseMap {
  [key: string]: Promise<unknown>;
}
 
const CACHE_NAME = 'SPORE_SDK_PROMISE';
 
let cache: TypePromiseMap = null;
 
if (typeof window === 'undefined') {
  cache = {};
} else {
  cache = get(window, CACHE_NAME) as TypePromiseMap;
  if (!cache) {
    cache = {};
    set(window, CACHE_NAME, cache);
  }
}
 
export function loadSdk(options: TypeLoadSdkOptions) {
  const conf: TypeLoadSdkOptions = {
    name: '',
    url: '',
    charset: '',
    ...options,
  };
 
  const {
    name,
    url,
    charset,
  } = conf;
 
  let pm = cache[name];
  if (pm) {
    return pm;
  }
 
  pm = getScript(url, {
    charset,
  }).then(() => get(window, name));
  cache[name] = pm;
 
  return pm;
}
 
export default loadSdk;