All files / src/utility binding.js

100% Statements 23/23
86.67% Branches 13/15
100% Functions 4/4
100% Lines 22/22

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 76 77 78 79                                  8x 2x     6x               6x 6x   6x 2x   4x     6x 5x 12x 2x       1x               3x                 2x   2x 1x 1x   1x     1x 1x     1x      
import {
  isNil,
  isString,
  startsWith,
  template,
} from 'lodash';
 
import logger from './logger';
 
export default {
  /*
  Resolves dynamic value.
  Dynamic value must start with equal (=) sign.
  If we detect dollar ($) sign after we try to resolve reference.
  Currently it only supports resolving references from store.
  */
  resolveDynamicValue(value, context) {
    if (isNil(context) || !isString(value) || !startsWith(value, '=')) {
      return value;
    }
 
    let binding = value.substring(1);
 
    /*
    For source of binding use registry or entire store.
    If there is a $ reference then use store first.
    If there is no $ reference then look in bindableElements registry.
    Cover both cases of usage. In Builder and in generated app.
    */
    const isRegistryAvailable = !isNil(context.$store) && !isNil(context.$store.getters.registry);
    let source = isRegistryAvailable ? context.$store.getters.registry : context.registry;
 
    if (startsWith(binding, '$')) {
      binding = binding.substring(1);
    } else {
      source = source.bindableElements;
    }
 
    if (source) {
      return binding.split('.').reduce((o, i) => {
        if (o[i]) return o[i];
        return '';
      }, source);
    }
 
    return value;
  },
  /*
  Sets expression as a compiled template function.
  Method can receive template options as second parameter.
  https://lodash.com/docs/4.17.11#templateSettings
  */
  setExpression(expression, options) {
    return template(expression, options);
  },
  /*
  Resolves expression by executing compiled template function.
  Second parameter is context that serves as data to template function.
  */
  resolveExpression(expressionFunction, context, defaultValue) {
    let value;
 
    try {
      // JSON.parse - expressionFunction is always returning String
      value = expressionFunction(context);
      try {
        value = JSON.parse(value);
      } catch (error) {
        return value;
      }
    } catch (error) {
      logger.warn('Error resolving expression');
      value = defaultValue;
    }
 
    return value;
  },
};