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

94.87% Statements 37/39
88.89% Branches 8/9
100% Functions 2/2
94.87% Lines 37/39

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 401x 1x 1x 1x 1x 1x 63x 49x 49x 63x 2x 2x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 238x 174x 174x 64x 64x 64x 64x     1x 1x  
const query = require('../../query');
 
/**
 * Return result of provided getType, throw error if no results are found and fatalError is true
 */
const checkQueryResult = (queryResult, getType, element, fatalError) => {
  if (queryResult[getType] !== undefined) {
    return queryResult[getType];
  }
  if (fatalError) {
    throw new Error(`No results found for provided query ${JSON.stringify(element.query)}.`);
  }
  return undefined;
};
 
/**
 * Get path element of the provided getType, if a query is found perform query and return result
 * @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 {Any} - element of provided getType, or undefined if not found
 */
const getSinglePathElement = (element, obj, tempObject, getType, priorPath, fatalError) => {
  if (element[getType] !== undefined) {
    return element[getType];
  }
  if (element.query) {
    const queryResult = query(element.query, obj, tempObject, false, priorPath);
    return checkQueryResult(queryResult, getType, element, fatalError);
  }
  return undefined;
};
 
module.exports = getSinglePathElement;