1 | import {Logger, LoggerFactory} from "../logger";
|
2 | import {Bean} from "../context/context";
|
3 | import {Qualifier} from "../context/context";
|
4 |
|
5 | @Bean('expressionService')
|
6 | export 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 |
|
18 | let func = <Function> expressionOrFunc;
|
19 | return func(params);
|
20 | } else if (typeof expressionOrFunc === 'string') {
|
21 |
|
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 |
|
33 |
|
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 |
|
41 |
|
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 |
|
51 | if (this.expressionToFunctionCache[expression]) {
|
52 | return this.expressionToFunctionCache[expression];
|
53 | }
|
54 |
|
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 |
|
59 | this.expressionToFunctionCache[expression] = theFunction;
|
60 |
|
61 | return theFunction;
|
62 | }
|
63 |
|
64 | private createFunctionBody(expression: any) {
|
65 |
|
66 |
|
67 | if (expression.indexOf('return') >= 0) {
|
68 | return expression;
|
69 | } else {
|
70 | return 'return ' + expression + ';';
|
71 | }
|
72 | }
|
73 | }
|