All files / latest/src/helpers/pathTransformer/src elementTransformer.js

100% Statements 64/64
100% Branches 18/18
100% Functions 7/7
100% Lines 64/64

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 651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 310x 310x 310x 310x 1x 1x 1x 1x 1x 294x 294x 294x 294x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 319x 9x 9x 319x 4x 4x 319x 12x 12x 319x 90x 90x 204x 204x 204x 1x 1x  
const queryTransformer = require('./queryTransformer');
 
/**
 * Checks whether element is a wildcard
 */
const isElementWildcard = (element) => ['*', '{$all}', '{*}'].indexOf(element) > -1;
 
/**
 * Checks whether element is a number
 */
const isNumberNumber = (element) => !Number.isNaN(Number(element));
 
/**
 * Checks whether element is of type string
 */
const isElementString = (element) => element && typeof element === 'string';
 
/**
 * Checks whether element is a query (surrounded by quotes)
 */
const isStringString = (element) => {
  const firstChar = element.charAt(0);
  const lastChar = element.charAt(element.length - 1);
  return (firstChar === lastChar && (firstChar === '"' || firstChar === "'"));
};
 
/**
 * Checks whether element is a query (surrounded by curly brackets)
 */
const isQueryQuery = (element) => {
  const firstChar = element.charAt(0);
  const lastChar = element.charAt(element.length - 1);
  return (firstChar === '{' && lastChar === '}');
};
 
/**
 * Removes opening and closing characters from string
 */
const removeOpeningClosingChars = (element) => element.substr(1, element.length - 2);
 
/**
 * Transforms each element of path into workable object representation
 * @param {String} element - string representation of path element
 * @returns {Object} - object with keyName the type of element and keyValue the value of element
 */
// eslint-disable-next-line complexity
const elementTransformer = (element) => {
  if (isElementWildcard(element)) {
    return { wildcard: true };
  }
  if (isElementString(element) && isStringString(element)) {
    return { string: removeOpeningClosingChars(element) };
  }
  if (isNumberNumber(element)) {
    return { number: Number(element) };
  }
  if (isElementString(element) && isQueryQuery(element)) {
    return { query: queryTransformer(removeOpeningClosingChars(element)) };
  }
 
  return { string: element };
};
 
module.exports = elementTransformer;