如何在 java 中递归遍历 graphql 文档并找到它达到的最深层次



我的目标是遍历一个 graphql Java 文档对象并返回最大深度。

示例:深度 0

{
name 
}

示例:深度 1

{
viewer{
viewerId
}
}

示例:深度 2

{
viewer{
albums{
albumId
}
}
}

示例:深度 2。 如您所见,两张专辑/歌曲都在同一个父"查看器"下

{
viewer{
albums{
albumId
}
songs{
songId
}
}
}

示例:深度 3

{
viewer{
albums{
tracks{
trackId
}
}
}
}

我已经编写了基本代码来遍历它,但我的代码不适用于深度 = 2 的第二个版本。 它返回深度 = 3 而不是 2。 原因是因为它在同一个父级下计数两次。 本质上的逻辑是这样的:深度 = 深度 + 1,只要一个字段有子字段。

import graphql.language.Document;
import graphql.language.Node;
import graphql.language.OperationDefinition;
public int checkDepthLimit(String query) {
Document document;
try {
document = documentParser.parseDocument(query);
} catch (Exception e) {}
Optional<Node> queryNode = document.getChildren().stream()
.filter(n -> (n.getClass() == OperationDefinition.class))
.findFirst();
return checkDepthLimit(queryNode.get());
}

private int checkDepthLimit(Node queryNode) {
int depth = 0;
String nodeType = queryNode.getClass().getSimpleName().toUpperCase();
if (nodeType.equals("FIELD")) {
if (!queryNode.getChildren().isEmpty()) {
depth += 1;
}
}
List<Node> nodeChildren = queryNode.getChildren();
for (int i = 0; i < nodeChildren.size(); i++) {
depth += checkDepthLimit(nodeChildren.get(i));
}
return depth;
}

String query = "{
viewer{
viewerId
}"
QueryComplexity c = new QueryComplexity();
int depth = c.checkDepthLimit(query);

我被困住了,如果对递归有更深入了解的人能够帮助我,我将不胜感激。

从 graphql-java v4.0 开始,有一个内置的QueryTraversal类来帮助你检查查询 AST 和一个用于限制深度的相关检测: MaxQueryDepthInstrumentation

只需像注册任何其他仪器一样注册它:

GraphQL runtime = GraphQL.newGraphQL(schema)
.instrumentation(new MaxQueryDepthInstrumentation(MAX_DEPTH))
.build();

还有MaxQueryComplexityInstrumentation。

GraphQL-SPQR(由我编写(还具有指定字段复杂性的声明性方法:

public static class PetService {
@GraphQLQuery(name = "pet")
@GraphQLComplexity("type == 'big' ? 10 : 2") //JavaScript expression calculating the complexity
public Pet findPet(@GraphQLArgument(name = "type") String type) {
return db.findPetByType(type);
}
}

您可以手动注册ComplexityAnalysisInstrumentation,与上面相同:

GraphQL runtime = GraphQL.newGraphQL(schema)
.instrumentation(new ComplexityAnalysisInstrumentation(new JavaScriptEvaluator(), MAX_DEPTH))
.build();

或者使用 SPQR 的GraphQLRuntime包装器:

GraphQL runtime = GraphQLRuntime.newGraphQL(schema)
.maximumQueryComplexity(maxComplexity)
.build();

错误是迭代子项的位置。正如你已经认识到的("数两次"(,你将每个孩子的深度添加到当前的深度,但你应该只添加最深的深度。

这确实可以解决问题:

List<Node> nodeChildren = queryNode.getChildren();
int maxChildDepth = 0;
for (int i = 0; i < nodeChildren.size(); i++) {
final int currentChildDepth = checkDepthLimit(nodeChildren.get(i));
maxChildDepth = Math.max(maxChildDepth, currentChildDepth);
}
depth += maxChildDepth;
return depth;

最新更新