验证REST API中的查询参数

问题描述 投票:0回答:1

我有一个接受查询参数的REST API。 The query parameters are valid if and only if at a time only one query parameter is passed and it is among the list of valid query parameters.

目前我的逻辑是:

我在地图中收集查询参数。然后检查它的大小。如果size> 1函数抛出错误。如果不是这种情况,则迭代地图,如果找到除有效参数之外的参数,则该函数会抛出错误。

例如:

if(queryParam.size()>1) {
        throw new FailureResponse();
    }

queryParam.forEach(e->{
        String key = e.getKey();
        if(!key.equalsIgnoreCase("p1") && !key.equalsIgnoreCase("p2")) {
            throw new FailureResponse();
        }

    });

但我认为这样违反了SOLID设计原则,即a class should be open for extension but closed for modification.

我还想到了creating a file and then reading the acceptable params,但这会增加API的响应时间,因为它涉及读取文件。

有没有什么方法可以保持和阅读有效的查询参数并且它不违反设计原则?

java rest api-design vert.x
1个回答
2
投票

你可以维护一个有效参数的枚举,并在适用的时候扩展枚举

public enum QueryParams{
      PARAM_1("param1"),
      PARAM_2("param2"),

      private String paramValue;
      QueryParams(String paramName){
        this.paramValue = paramValue();
      }
      public void getParamValue(){
         return this.value;
      }
}

然后你可以迭代这个枚举的值集来过滤掉无效的值

List<String> validParams = Arrays.asList(QueryParams.values()).stream().map(QueryParams::getParamValue).collect(Collectors.toList());
    queryParams.removeAll(validParams);
    if(queryParams.size()!=0) {
        throw new FailureResponse();
    }
}

这有助于您在没有任何更改的情况下维护API类,无论何时添加新参数,只需扩展枚举,所有其余内容都会自动扩展,因为它全部取决于枚举中的值。

© www.soinside.com 2019 - 2024. All rights reserved.