All files / latest/src/helpers/pathElements/getMultiple index.js

100% Statements 41/41
100% Branches 8/8
100% Functions 2/2
100% Lines 41/41

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 421x 1x 1x 1x 1x 1x 55x 3x 3x 55x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 196x 196x 141x 196x 55x 55x 91x 91x 91x 91x 55x 55x 193x 193x 1x 1x  
const query = require('../../query');
 
/**
 * Validate results, throw error if no results are found and fatalError is true
 */
const validateResults = (results, fatalError, element) => {
  if (results.length === 0 && fatalError) {
    throw new Error(`No results found for provided query ${JSON.stringify(element.query)}.`);
  }
};
 
/**
 * Get path elements of the provided getType, if a query is found perform query and
 * return all results that match
 * @param {Object} element - input element with number, string or query key
 * @param {Object} obj - initial object
 * @param {Object} tempObject - remainder of initial object found at priorPath
 * @param {String} getType - getType is either 'string' or 'number'
 * @param {Array} priorPath - array representation of already processed path
 * (path at current iteration)
 * @param {Boolean} fatalError - boolean indicating if fatalError should be thrown
 * if no match is found for query
 * @returns {Array} - elements of provided getType, or empty array if not found
 */
const getMultiplePathElements = (element, obj, tempObject, getType, priorPath, fatalError) => {
  const results = [];
  if (element[getType] !== undefined) {
    results.push(element);
  } else if (element.query) {
    const queryResult = query(element.query, obj, tempObject, true, priorPath);
    queryResult.forEach((result) => {
      if (result[getType] !== undefined) {
        results.push(result);
      }
    });
    validateResults(results, fatalError, element);
  }
  return results;
};
 
module.exports = getMultiplePathElements;