all files / src/lib/ adapter.js

93.75% Statements 15/16
88.89% Branches 8/9
100% Functions 2/2
92.31% Lines 12/13
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                                                                                     
/**
 * Exports the core adapter object
 * @namespace adapter
 */
export const adapter = {}
 
/**
 * Stores the adapters in memory
 * @property {Object}
 */
adapter.store = {}
 
/**
 * Adds an adapter to the store
 * @param {Object} a The adapter to add
 */
adapter.add = (a) => {
  // Ensure properties are defined
  if (!a.name || !a.source || !a.config) {
    throw new Error('Adapter must contain a name, source and config' + JSON.stringify({
      name: a.name,
      source: a.source,
      config: a.config
    }))
  }
  // Add to memory
  adapter.store[a.name] = {
    source: a.source,
    config: a.config
  }
}
 
/**
 * Gets adapter and calls config
 * @memberof adapter
 * @param {String} adapter The adapter to require/import
 * @returns {Object} Adapter
 */
adapter.init = (a) => {
  let adapterObj
  // Ensure model is defined
  if (!adapter.store[a]) {
    throw new Error('Adapter not defined')
  }
  const source = adapter.store[a].source
  Eif (typeof source === 'function') {
    adapterObj = source
  } else {
    adapterObj = require(source)
  }
  // Instantiate adapter
  return new adapterObj(adapter.store[a].config)
}