4

我在我的项目中使用angular2-query-builder 。此外,后端项目使用 Java、Spring boot 和 Rulebook 作为规则引擎来触发由 angular2-query-builder 生成的规则。所以我需要从 angular2-query-builder 的输出中做一个逻辑表达式。

这是一个由查询生成器生成的类型脚本对象。

  query = {
    condition: 'and',
    rules: [
      {field: 'age', operator: '<=', value: '16'},
      {field: 'gender', operator: '=', value: 'm'}
    ]
  };

我在后端制作的映射模型类:

RuleSet {
    String field;
    String value;
    String operator;
    String entity;
    String condition;
    RuleSet[] rules;
//...getters and setters}

我需要(age <= 16) && (gender = 'm')从对象中获取。

4

2 回答 2

2

制作递归方法以遍历规则

private void decode(RuleSet[] rules, List<String> expressions, String condition) {
        for (int i = 0; i < rules.length; i++) {
            RuleSet item = rules[i];
            if (item.rules == null) {
                expressions.add(merge("(", item.field, item.operator, item.value, ")"));
                if (i != rules.length - 1) {
                    expressions.add(condition);
                }
            } else {
                condition = item.getCondition();
                expressions.add("(");
                decode(item.rules, expressions, condition);
                expressions.add(")");
            }
        }
    }
public String merge(String... strings) {
    StringBuilder result = new StringBuilder();
    for (String item : strings) {
        if (item != null) {
            result.append(item);
        }
    }
    return result.toString();
}

然后这样称呼它:

List<String> expressions = new ArrayList<>();
decode(querySchema.ruleSet.rules, expressions, querySchema.ruleSet.condition);

通过将所有表达式项添加到字符串对象中。将生成逻辑表达式。

于 2018-08-21T09:39:48.440 回答
1

参考 ramin,typeScript 的相同实现

首先将模型定义为:

export class RuleSet {
    field?  : string;
    value? : string | string[] | number;
    operator? : string;
    entity ?: string;
    condition ?: string;
    rules ?: RuleSet[];
}

然后定义解码函数:

  //params : [{field: 'age', operator: '<=', value: '16'},{field: 'gender', operator: 
  //'=', value: 'm'}],'and'
  decodeQuery(rules : RuleSet[], condition : string) {
    for (var i = 0; i < rules.length; i++) {
        var item :RuleSet = rules[i];
        if (item.rules == null) {
            this.expression = this.expression + this.mergeString("(", item.field, item.operator, item.value, ")");
            if (i != rules.length - 1) {
                this.expression = this.expression + " " + condition + " ";
            }
        } else {
            condition = item.condition;
            this.expression = this.expression + "(";
            this.decodeQuery(item.rules, condition);
            this.expression = this.expression + ")";
        }
    }
  }

  mergeString(bracket1,field,operator,value,bracket2) {
    var mergedString = bracket1 + " " + field + " " + operator + " " + value + " " + bracket2 ;
    return mergedString;
  }

称之为:

expression : string = "";
this.decodeQuery(query.rules,query.condition);

结果输出如下:

(age <= 16) && (gender = 'm')
于 2020-05-17T19:46:59.017 回答