2020-10-09 19:35:46 +02:00
|
|
|
import { ContextKeyExpr, ContextKeyExpression } from './contextkey/contextkey';
|
|
|
|
|
2020-10-18 22:52:10 +02:00
|
|
|
export default class WhenClause {
|
2020-10-09 19:35:46 +02:00
|
|
|
|
|
|
|
private expression_:string;
|
2020-10-18 22:52:10 +02:00
|
|
|
private validate_:boolean;
|
2020-10-09 19:35:46 +02:00
|
|
|
private rules_:ContextKeyExpression = null;
|
|
|
|
|
2020-10-18 22:52:10 +02:00
|
|
|
constructor(expression:string, validate:boolean) {
|
2020-10-09 19:35:46 +02:00
|
|
|
this.expression_ = expression;
|
2020-10-18 22:52:10 +02:00
|
|
|
this.validate_ = validate;
|
2020-10-09 19:35:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private createContext(ctx: any) {
|
|
|
|
return {
|
|
|
|
getValue: (key: string) => {
|
|
|
|
return ctx[key];
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private get rules():ContextKeyExpression {
|
|
|
|
if (!this.rules_) {
|
|
|
|
this.rules_ = ContextKeyExpr.deserialize(this.expression_);
|
|
|
|
}
|
2020-10-18 22:52:10 +02:00
|
|
|
|
2020-10-09 19:35:46 +02:00
|
|
|
return this.rules_;
|
|
|
|
}
|
|
|
|
|
|
|
|
public evaluate(context:any):boolean {
|
2020-10-18 22:52:10 +02:00
|
|
|
if (this.validate_) this.validate(context);
|
2020-10-09 19:35:46 +02:00
|
|
|
return this.rules.evaluate(this.createContext(context));
|
|
|
|
}
|
|
|
|
|
2020-10-18 22:52:10 +02:00
|
|
|
public validate(context:any) {
|
|
|
|
const keys = this.rules.keys();
|
|
|
|
for (const key of keys) {
|
|
|
|
if (!(key in context)) throw new Error(`No such key: ${key}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-09 19:35:46 +02:00
|
|
|
}
|