在 REST 中验证查询参数 API
Validating Query Params in REST API
我有一个接受查询参数的 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();
}
});
但我认为这样我违反了 a class should be open for extension but closed for modification.
的 SOLID 设计原则
我还从中想到了 creating a file and then reading the acceptable params
,但这会增加 API 的响应时间,因为它涉及读取文件。
有什么方法可以让我保留和读取有效的查询参数并且不违反设计原则吗?
您可以维护有效参数的枚举并在适用时扩展枚举,如
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 class 不做任何更改,无论何时添加新参数,只需扩展枚举,其余所有内容都会自动扩展,因为这完全取决于中的值枚举。
我有一个接受查询参数的 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();
}
});
但我认为这样我违反了 a class should be open for extension but closed for modification.
我还从中想到了 creating a file and then reading the acceptable params
,但这会增加 API 的响应时间,因为它涉及读取文件。
有什么方法可以让我保留和读取有效的查询参数并且不违反设计原则吗?
您可以维护有效参数的枚举并在适用时扩展枚举,如
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 class 不做任何更改,无论何时添加新参数,只需扩展枚举,其余所有内容都会自动扩展,因为这完全取决于中的值枚举。