aviatorscript icon indicating copy to clipboard operation
aviatorscript copied to clipboard

多级字段取值自动判空能力

Open noShampoo opened this issue 2 years ago • 0 comments

背景

在表达式使用的过程中,我们经常会通过表达式从上下文中进行取值。例如:

JSONObject context = new JSONObject();
JSONObject result = new JSONObject();
Map<String, String> featureMap = Maps.newHashMap();
featureMap.put("f1", "1L");
result.put("featureMap", featureMap);
context.put("result", result);

有一个context作为上下文,需要取其featureMap的f1字段值,我们的表达式会写成

## $=context

$.result.featureMap.f1

存在的问题

但是,这种写法需要使用方自己保证 $、result、featureMap都必须为非空的字段,否则aviator会在执行过程中抛出异常;而在使用过程中我们通常是无法确保的,所以需要进行判空操作。此时,表达式就需要写成如下形式:

if($!=nil) {
	if($.result!=nil) {
  		if($.result.featureMap!=nil) {
    		return $.result.featureMap.f1;
  		}
	}
}

需求期望

这样的写法虽然能够保障表达式的正常执行,但是在多级字段的取值使用中对用户是不太友好的,我们希望能够可以通过类似mvel的方法直接进行判空,如下:

$.?result.?featureMap.?f1

通过.?的语法对其左值进行判空,当其左值为空时直接返回空

noShampoo avatar Jul 21 '23 02:07 noShampoo