All files / src/modules fake.js

100% Statements 75/75
100% Branches 19/19
100% Functions 2/2
100% Lines 75/75

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 65 66 67 68 69 70 71 72 73 74 75 761x 1x 1x 22x 22x 1x 1x 59x 59x 59x 59x 59x 2x 2x 57x 57x 57x 57x 57x 180x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 107x 57x 57x 57x 76x 88x 88x 87x 88x 2x 2x 86x 86x 86x 86x 88x 5x 5x 5x 2x 1x 1x 1x 1x 1x 88x 81x 81x 85x 85x 76x 57x 57x 57x 57x 57x 57x 1x  
// TODO: Methods that use mustachestring as parameter don't work
export class Fake {
  constructor(pure) {
    this.pure = pure;
  }
 
  parse(str) {
    const fakeStringRegex = /(\w+)\.(\w+)(?:\((.*)\))?/g;
    const paramsRegex = /(?:\((.*)\))/g;
 
    // if incoming str parameter is not provided, return error message
    if (typeof str !== 'string' || str.length === 0) {
      throw new Error('string parameter is required!');
    }
 
    const parsed = this.pure.helpers.mustacheParse(str);
    let result = {};
 
    parsed.forEach(item => {
      if (item[0] === 'name' || item[0] === '&') {
        let module;
        let method;
        let args;
 
        item[1].replace(fakeStringRegex, (_, a, b, c) => {
          module = a;
          method = b;
          args = c;
        });
 
        result = {
          ...result,
          [module]: {
            ...result[module],
            [method]: args
          }
        };
      }
    });
 
    Object.keys(result).forEach(module => {
      Object.keys(result[module]).forEach(method => {
        if (
          typeof this.pure[module] === 'undefined' ||
          typeof this.pure[module][method] === 'undefined'
        ) {
          throw new Error(`${module}.${method} doesn't exist inside pure scope`);
        }
 
        const params = result[module][method];
        let args = '';
 
        if (params) {
          try {
            args = JSON.parse(params);
          } catch (e) {
            if (params[0] === '{') {
              throw new Error(`Params provided doesn't match JSON standard type. Error: ${e}`);
            }
 
            args = params;
          }
        } else {
          args = params;
        }
 
        result[module][method] = this.pure[module][method](args);
      });
    });
 
    const strFixed = str.replace(paramsRegex, '');
 
    return this.pure.helpers.mustache({ str: strFixed, data: result });
  }
}