UNPKG

3.13 kBPlain TextView Raw
1import {Logger, LoggerFactory} from "../logger";
2import {Bean} from "../context/context";
3import {Qualifier} from "../context/context";
4
5@Bean('expressionService')
6export class ExpressionService {
7
8 private expressionToFunctionCache = <any>{};
9 private logger: Logger;
10
11 private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) {
12 this.logger = loggerFactory.create('ExpressionService');
13 }
14
15 public evaluate(expressionOrFunc: Function | string, params: any): any {
16 if (typeof expressionOrFunc === 'function') {
17 // valueGetter is a function, so just call it
18 let func = <Function> expressionOrFunc;
19 return func(params);
20 } else if (typeof expressionOrFunc === 'string') {
21 // valueGetter is an expression, so execute the expression
22 let expression = <string> expressionOrFunc;
23 return this.evaluateExpression(expression, params);
24 } else {
25 console.error('ag-Grid: value should be either a string or a function', expressionOrFunc);
26 }
27 }
28
29 private evaluateExpression(expression: string, params: any): any {
30 try {
31 let javaScriptFunction = this.createExpressionFunction(expression);
32 // the params don't have all these values, rather we add every possible
33 // value a params can have, which makes whatever is in the params available.
34 let result = javaScriptFunction(params.value, params.context,
35 params.oldValue, params.newValue, params.value, params.node,
36 params.data, params.colDef, params.rowIndex, params.api, params.columnApi,
37 params.getValue, params.column, params.columnGroup);
38 return result;
39 } catch (e) {
40 // the expression failed, which can happen, as it's the client that
41 // provides the expression. so print a nice message
42 console.log('Processing of the expression failed');
43 console.log('Expression = ' + expression);
44 console.log('Exception = ' + e);
45 return null;
46 }
47 }
48
49 private createExpressionFunction(expression: any) {
50 // check cache first
51 if (this.expressionToFunctionCache[expression]) {
52 return this.expressionToFunctionCache[expression];
53 }
54 // if not found in cache, return the function
55 let functionBody = this.createFunctionBody(expression);
56 let theFunction = new Function('x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, columnApi, getValue, column, columnGroup', functionBody);
57
58 // store in cache
59 this.expressionToFunctionCache[expression] = theFunction;
60
61 return theFunction;
62 }
63
64 private createFunctionBody(expression: any) {
65 // if the expression has the 'return' word in it, then use as is,
66 // if not, then wrap it with return and ';' to make a function
67 if (expression.indexOf('return') >= 0) {
68 return expression;
69 } else {
70 return 'return ' + expression + ';';
71 }
72 }
73}