bdp*_*ish 2 java graphql graphql-java
我正在寻找使用其他对象类型将字段值传递给已解析的字段。
如果我有“客户>用户>个人资料”,则可以用另一种方式输入-如何将客户中的CustomerID字段值作为参数或变量传递给个人资料,以便正确解析?
(从graphql-java v12开始)有5种可能性可以DataFetcher
在任何级别上向解析器()提供信息:
1)直接在查询中传递它们(可能在多个级别上):
{customer(id: 3) {
user {
profile(id: 3) {
name
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
2)从源对象获取值
所述源是封闭的查询的结果。在您的情况下,customer
查询的源是根上下文(无论您在查询执行时提供了什么内容,例如graphQL.execute(query, rootContext)
)。查询
的来源user
是customer
返回的任何查询,大概是某个Customer
实例。查询
的来源profile
是user
查询返回的任何内容,大概是一个User
实例。您可以通过来获取消息来源DataFetchingEnvironment#getSource()
。因此,如果User
包含CustomerID
您所追求的,只需通过获得((User) env.getSource()).getCustomerId()
。如果不是,请考虑将结果包装到一个包含子查询中所需全部内容的对象中。
3)使用共享上下文传递值
例如,您可以使用a ConcurrentHashMap
作为上下文:
ExecutionInput input = ExecutionInput.newExecutionInput()
.query(operation)
.context(new ConcurrentHashMap<String, Object>())
.build()
graphQL.execute(query, input);
Run Code Online (Sandbox Code Playgroud)
然后,在DataFetcher
for中customer
,将存储CustomerID
到其中:
Customer customer = getCustomer();
Map<String, Object> context = env.getContext();
context.put("CustomerID", customer.getId());
Run Code Online (Sandbox Code Playgroud)
稍后,在DataFetcher
for中profile
,您可以从上下文中获取它:
Map<String, Object> context = env.getContext();
context.get("CustomerID");
Run Code Online (Sandbox Code Playgroud)
ConcurrentHashMap
可以使用类型化的对象代替,但是必须确保字段是volatile
getters / setter synchronized
或其他线程安全的。
这种方式是有状态的,因此是最难管理的,因此仅在所有其他方式均失败时才使用它。
4)直接获取传递给父字段的参数(自graphql-java v11起可能)
ExecutionStepInfo stepInfo = dataFetchingEnvironment.getExecutionStepInfo();
stepInfo.getParent().getArguments(); // get the parent arguments
Run Code Online (Sandbox Code Playgroud)
5)使用本地上下文传递值(自graphql-java v12起可能)
而不是直接返回结果,而是将其包装到中DataFetcherResult
。这样,您还可以通过附加任何对象,所有对象localContext
均可DataFetcher
通过DataFetchingEnvironment#getLocalContext()