All files / src/utility bundleInjector.js

79.07% Statements 34/43
72.73% Branches 16/22
72.73% Functions 8/11
78.95% Lines 30/38

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 75 76 77 78 79    30x   15x                     15x 38x 38x 38x 38x   38x 38x   38x 30x   8x 8x 8x     38x 38x 38x 38x           38x                               25x 25x 25x   25x 40x     25x 30x     25x 8x     25x   25x      
import { filter, map, indexOf } from 'lodash';
 
const isGlobalAvailable = global => !!window[global];
 
const startAvailabilityInterval = (global, resolve) => {
  const availabilityInterval = setInterval(() => {
    if (isGlobalAvailable(global)) {
      resolve(global);
      clearInterval(availabilityInterval);
    }
  }, 100);
 
  return availabilityInterval;
};
 
const addBundleItem = (item, type, bundleName, bundleBaseUrl) => {
  const attr = type === 'script' ? 'src' : 'href';
  const itemName = type === 'script' ? item.script : item;
  const itemGlobal = item.global;
  let checkInterval = null;
 
  const script = document.createElement(type);
  script.setAttribute(attr, `${bundleBaseUrl}/bundles/${bundleName}/latest/${itemName}`);
 
  if (type === 'script') {
    document.body.appendChild(script);
  } else {
    script.rel = 'stylesheet';
    script.type = 'text/css';
    document.head.appendChild(script);
  }
 
  return new Promise((resolve, reject) => {
    script.onload = () => {
      Eif (type === 'link' || isGlobalAvailable(itemGlobal)) {
        resolve(itemGlobal);
      } else {
        checkInterval = startAvailabilityInterval(itemGlobal, resolve);
      }
    };
 
    script.onerror = () => {
      if (checkInterval) clearInterval(checkInterval);
      reject(bundleName);
    };
  });
};
 
export default {
  /**
    * Load bundles method.
    * @param {object} bundle - Bundle object that contains bundle information.
    * @param {object} config - Config object width properties:
    * scripts, baseURL, styles.
    * @return {object} promise.
    */
  loadBundles(bundle, config) {
    let scripts = [];
    let promises = [];
    let styles = [];
 
    Eif (bundle.scripts) {
      scripts = filter(bundle.scripts, script => indexOf(config.scripts, script.type) > -1);
    }
 
    if (scripts.length > 0) {
      promises = map(scripts, script => addBundleItem(script, 'script', bundle.name, config.baseURL));
    }
 
    if (bundle.styles && config.styles) {
      styles = map(bundle.styles, style => addBundleItem(style, 'link', bundle.name, config.baseURL));
    }
 
    promises = promises.concat(styles);
 
    return Promise.all(promises);
  },
};