All files / copacetic/lib/util injector.js

100% Statements 14/14
100% Branches 11/11
100% Functions 4/4
100% Lines 13/13

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            63x                   108x 121x   121x             105x       3x 2x         157x 157x   2x 1x   1x         63x  
/**
 * @class
 * @classdesc requires peer dependencies
 */
class Injector {
  constructor (require) {
    this.require = require
  }
 
  /**
   * @param {Array<String>} moduleNames An array of module names
   * @param {Boolean} optional At least one module must be successfullly resolved, or
   * an error is thrown
   * @return {Object} A resolved dependency or undefined if none are found
   */
  provideAny (moduleNames, optional = true) {
    for (const name of moduleNames) {
      const exported = this.provideOne(name, true)
 
      if (exported) {
        /**
         * A resolved, optional peer dependency
         * @typedef {Object} Injector~Dependency
         * @property {String} name
         * @property {Module} exported
         */
        return { name, exported }
      }
    }
 
    if (!optional) {
      throw new Error(`Could not resolve any of ${moduleNames}, but at least one was required`)
    }
  }
 
  provideOne (moduleName, optional = false, allowSystem = false) {
    try {
      return this.require(moduleName, { optional })
    } catch (e) {
      if (e.message.indexOf('not found') > -1 && allowSystem) {
        return require(moduleName)
      }
      throw e
    }
  }
}
 
module.exports = require => new Injector(require)