DGS框架支持突变,其结构与数据提取器相同,使用@DgsData注解。下面是一个突变的简单例子。
type Mutation {
addRating(title: String, stars: Int):Rating
}
type Rating {
avgStars: Float
}
@DgsComponent
public class RatingMutation {
@DgsData(parentType = "Mutation", field = "addRating")
public Rating addRating(DataFetchingEnvironment dataFetchingEnvironment) {
int stars = dataFetchingEnvironment.getArgument("stars");
if(stars < 1) {
throw new IllegalArgumentException("Stars must be 1-5");
}
String title = dataFetchingEnvironment.getArgument("title");
System.out.println("Rated " + title + " with " + stars + " stars") ;
return new Rating(stars);
}
}
注意,上面的代码通过调用DataFetchingEnvironment.getArgument方法为Mutation检索输入数据,就像数据提取器为其参数所做的那样。
在上面的例子中,输入是两个标准的标量类型。你也可以使用复杂的类型,你应该在你的模式中把这些定义为输入类型。输入类型几乎与GraphQL中的类型相同,但有一些额外的规则。
根据GraphQL规范,输入类型应该总是以Map的形式传递给数据提取器。这意味着输入类型的DataFetchingEnvironment.getArgument是一个Map,而不是你可能有的Java/Kotlin表示。该框架有一个围绕这个问题的便利机制,这将在接下来讨论。让我们先看看一个直接使用DataFetchingEnvironment的例子。
type Mutation {
addRating(input: RatingInput):Rating
}
input RatingInput {
title: String,
stars: Int
}
type Rating {
avgStars: Float
}
--------------------------------
@DgsComponent
public class RatingMutation {
@DgsData(parentType = "Mutation", field = "addRating")
public Rating addRating(DataFetchingEnvironment dataFetchingEnvironment) {
//输入类型应该总是以Map的形式传递给数据提取器
Map<String,Object> input = dataFetchingEnvironment.getArgument("input");
//为Mutation检索输入数据
RatingInput ratingInput = new ObjectMapper().convertValue(input, RatingInput.class);
System.out.println("Rated " + ratingInput.getTitle() + " with " + ratingInput.getStars() + " stars") ;
return new Rating(ratingInput.getStars());
}
}
class RatingInput {
private String title;
private int stars;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
}
该框架使获取输入参数变得更加容易。你可以指定参数作为数据获取器的方法参数。
@DgsComponent
public class RatingMutation {
@DgsData(parentType = "Mutation", field = "addRating")
public Rating addRating(@InputArgument("input") RatingInput ratingInput) {
//No need for custom parsing anymore!
System.out.println("Rated " + ratingInput.getTitle() + " with " + ratingInput.getStars() + " stars") ;
return new Rating(ratingInput.getStars());
}
}
@InputArgument注解对于指定输入参数的名称很重要,因为参数可以以任何顺序指定。如果没有注解,框架会尝试使用参数名称,但这只有在代码以特定的编译器设置进行编译时才能实现。输入类型参数可以与DataFetchingEnvironment参数相结合。
@DgsComponent
public class RatingMutation {
@DgsData(parentType = "Mutation", field = "addRating")
public Rating addRating(@InputArgument("input") RatingInput ratingInput, DataFetchingEnvironment dfe) {
//No need for custom parsing anymore!
System.out.println("Rated " + ratingInput.getTitle() + " with " + ratingInput.getStars() + " stars") ;
System.out.println("DataFetchingEnvironment: " + dfe.getArgument(ratingInput));
return new Rating(ratingInput.getStars());
}
}
建造者模式