有 5 种可能性(从 graphql-java v12 开始)向解析器提供信息(DataFetcher
)在任何级别:
1)直接在查询中传递它们(可能在多个级别上):
{customer(id: 3) {
user {
profile(id: 3) {
name
}
}
}
}
2) 获取值source object
The source是封闭查询的结果。
就您而言,来源customer
query 是根(无论您在查询执行时提供什么,例如
graphQL.execute(ExecutionInput.newExecutionInput()
.query(query)
.root(root)
.build())
的来源user
查询是任意的customer
返回查询,大概是一些Customer
实例。
的来源profile
查询是任何user
返回的查询,大概是User
实例。
您可以通过以下方式获取源代码DataFetchingEnvironment#getSource()
。因此,如果User
包含CustomerID
你正在寻找,只需通过((User) env.getSource()).getCustomerId()
。如果没有,请考虑将结果包装到一个对象中,该对象将包含子查询中所需的所有内容。
3)使用共享上下文传递值
graphql-java 传递一个实例GraphQLContext
可供所有解析器使用。所以,里面DataFetcher
for customer
,您可以存储CustomerID
进去:
Customer customer = getCustomer();
GraphQLContext context = env.getContext();
context.put("CustomerID", customer.getId());
后来,在里面DataFetcher
for profile
,你可以从上下文中得到它:
String customerId = env.getContext().get("CustomerID");
要初始化上下文,请在执行查询时传递它:
ExecutionInput input = ExecutionInput.newExecutionInput()
.query(operation)
.graphQLContext(new HashMap<>())
.build()
graphQL.execute(query, input);
这种方式是有状态的,因此最难管理,因此只有在其他方法都失败时才使用它。
4) 直接获取传递给父字段的参数
ExecutionStepInfo stepInfo = dataFetchingEnvironment.getExecutionStepInfo();
stepInfo.getParent().getArguments(); // get the parent arguments
5)使用传递值local context
不是直接返回结果,而是将其包装成DataFetcherResult
。这样您还可以将任何对象附加为localContext
所有孩子都可以使用DataFetcher
s via DataFetchingEnvironment#getLocalContext()