-
Notifications
You must be signed in to change notification settings - Fork 2
/
engine.ts
70 lines (59 loc) · 2.24 KB
/
engine.ts
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
import { BINDINGS_PARAM_KEY, DATA_PARAM_KEY } from './constants';
import { JsonTemplateLexer } from './lexer';
import { JsonTemplateParser } from './parser';
import { JsonTemplateTranslator } from './translator';
import { EngineOptions, Expression } from './types';
import { CommonUtils } from './utils';
export class JsonTemplateEngine {
private readonly fn: Function;
private constructor(fn: Function) {
this.fn = fn;
}
static create(templateOrExpr: string | Expression, options?: EngineOptions): JsonTemplateEngine {
return new JsonTemplateEngine(this.compileAsAsync(templateOrExpr, options));
}
static createAsSync(
templateOrExpr: string | Expression,
options?: EngineOptions,
): JsonTemplateEngine {
return new JsonTemplateEngine(this.compileAsSync(templateOrExpr, options));
}
private static compileAsSync(
templateOrExpr: string | Expression,
options?: EngineOptions,
): Function {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
return Function(DATA_PARAM_KEY, BINDINGS_PARAM_KEY, this.translate(templateOrExpr, options));
}
private static compileAsAsync(
templateOrExpr: string | Expression,
options?: EngineOptions,
): Function {
return CommonUtils.CreateAsyncFunction(
DATA_PARAM_KEY,
BINDINGS_PARAM_KEY,
this.translate(templateOrExpr, options),
);
}
static parse(template: string, options?: EngineOptions): Expression {
const lexer = new JsonTemplateLexer(template);
const parser = new JsonTemplateParser(lexer, options);
return parser.parse();
}
static translate(templateOrExpr: string | Expression, options?: EngineOptions): string {
if (typeof templateOrExpr === 'string') {
return this.translateTemplate(templateOrExpr, options);
}
return this.translateExpression(templateOrExpr);
}
private static translateTemplate(template: string, options?: EngineOptions): string {
return this.translateExpression(this.parse(template, options));
}
private static translateExpression(expr: Expression): string {
const translator = new JsonTemplateTranslator(expr);
return translator.translate();
}
evaluate(data: any, bindings: Record<string, any> = {}): any {
return this.fn(data ?? {}, bindings);
}
}