All files / lib/dynamic-form-element dynamic-form-element-expression.ts

100% Statements 16/16
100% Branches 1/1
100% Functions 4/4
100% Lines 16/16

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                              14x 14x 14x 14x     14x     7x       25x 25x 24x 24x   1x 1x 1x 1x   1x 1x        
import { DynamicFormElement } from '../dynamic-form-element/dynamic-form-element';
import { DynamicFormExpression } from '../dynamic-form-expression/dynamic-form-expression';
import { DynamicFormErrorHandler } from '../dynamic-form-error/dynamic-form-error.handler';
import { DynamicFormError } from '../dynamic-form-error/dynamic-form-error';
import { DynamicFormErrorType } from '../dynamic-form-error/dynamic-form-error-type';
import { DynamicFormElementExpressionData } from './dynamic-form-element-expression-data';
import { DynamicFormElementExpressionFunc } from './dynamic-form-element-expression-func';
 
export class DynamicFormElementExpression<
  Data extends DynamicFormElementExpressionData = DynamicFormElementExpressionData,
  Func extends DynamicFormElementExpressionFunc<Data> = DynamicFormElementExpressionFunc<Data>
> implements DynamicFormExpression<Data, Func> {
  private _errorMessage: string;
 
  constructor(
    readonly key: string,
    readonly element: DynamicFormElement,
    readonly func: Func,
    protected errorHandler: DynamicFormErrorHandler,
  ) {}
 
  get value(): any { return this.tryEvaluate(); }
 
  protected evaluate(): any {
    return this.func(this.element.expressionData as Data);
  }
 
  protected tryEvaluate(): any {
    try {
      const value = this.evaluate();
      this._errorMessage = undefined;
      return value;
    } catch (error) {
      if (this._errorMessage !== error.message) {
        const type = DynamicFormErrorType.ExpressionEvaluation;
        const message = 'Expression evaluation';
        this.errorHandler.handle(new DynamicFormError(type, message, error));
      }
      this._errorMessage = error.message;
      return undefined;
    }
  }
}