type Query { shows: [Show]}type Show { title: String actors: [Actor]}
我们可以用一个 datafetcher 来实现这个 schema。
@DgsComponentpublicclassShowDataFetcher{@DgsData(parentType="Query",field="shows")publicList<Show>shows(){ //Load shows from a database and return the list of Show objectsreturn shows;}}
如果没有设置参数 field ,则默认会将方法名称当做 field 名称。 @DgsQuery, @DgsMutation 以及 @DgsSubscription 注解是定义 datafetchers 在 Query, Mutation 和 Subscription 类型的快速方式。与下面的定义方式效果一样。
@DgsData(parentType = "Query", field = "shows")
public List<Show> shows() { .... }
// The "field" argument is omitted. It uses the method name as the field name.
@DgsData(parentType = "Query")
public List<Show> shows() { .... }
// The parentType is "Query", the field name is derived from the method name.
@DgsQuery
public List<Show> shows() { .... }
// The parentType is "Query", the field name is explicitly specified.
@DgsQuery(field = "shows")
public List<Show> shows() { .... }
{
shows {
title
}
}
@DgsData(parentType = "Query", field = "shows")
public List<Show> shows() {
//Load shows, which doesn't include "actors"
return shows;
}
@DgsData(parentType = "Show", field = "actors")
public List<Actor> actors(DgsDataFetchingEnvironment dfe) {
Show show = dfe.getSource();
actorsService.forShow(show.getId());
return actors;
}
@DgsData(parentType = "Query", field = "shows")
public List<Show> shows(@InputArgument String title, @InputArgument ShowFilter filter)
# name is a nullable input argument
hello(name: String): String
fun hello(@InputArgument hello: String?)
type Query {
hello(people:[Person]): String
}
public String hello(@InputArgument(collectionType = Person.class) List<Person> people)
public List<Show> shows(@InputArgument(collectionType = ShowFilter.class) Optional<ShowFilter> filter)
type Query {
shows: [Show]
}
@DgsData(parentType = DgsConstants.QUERY_TYPE, field = DgsConstants.QUERY.Shows)
public List<Show> shows() {}
public String hello(@RequestHeader String host)
@DgsData(parentType = "Query", field = "serverName")
public String serverName(DgsDataFetchingEnvironment dfe) {
DgsRequestData requestData = DgsContext.getRequestData(dfe);
return ((ServletWebRequest)requestData.getWebRequest()).getRequest().getServerName();
}
@Component
public class MyContextBuilder implements DgsCustomContextBuilder<MyContext> {
@Override
public MyContext build() {
return new MyContext();
}
}
public class MyContext {
private final String customState = "Custom state!";
public String getCustomState() {
return customState;
}
}
@DgsData(parentType = "Query", field = "withContext")
public String withContext(DataFetchingEnvironment dfe) {
MyContext customContext = DgsContext.getCustomContext(dfe);
return customContext.getCustomState();
}