All files / latest/src/handlers/basic parse.js

93.33% Statements 28/30
77.78% Branches 7/9
100% Functions 3/3
93.33% Lines 28/30

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 311x 1x 1x 1x 6x 6x 6x 3x 3x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 726x     726x 726x 1x 1x  
/**
 * attempt to parse
 */
const attemptToParse = (value) => {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
};
 
/**
 * attempt to parse, or parse depending on safeParse variable
 */
const goParse = (value, safeParse) => (safeParse ? attemptToParse(value) : JSON.parse(value));
 
/**
 * Parses input value if it is stringified
 * @param {any} value - (stringified) object/array
 * @param {boolean} safeParse - boolean, if true no error is thrown if value is not parsable
 * @returns {any} parsed value, or in case of safeParse input value if value is not parsable
 */
const parse = (value, safeParse) => {
  if (value && typeof value === 'string') {
    return goParse(value, safeParse);
  }
  return value;
};
 
module.exports = parse;