继承GraphQLScalarType类,然后重写父类的构造器,传入三个参数。这个方法已经过时了,最新的构造器需要传入5个参数,都有非空校验
private GraphQLScalarType(String name, String description, Coercing<?, ?> coercing, List<GraphQLDirective> directives, List<GraphQLAppliedDirective> appliedDirectives, ScalarTypeDefinition definition, List<ScalarTypeExtensionDefinition> extensionDefinitions, String specifiedByUrl) {
Assert.assertValidName(name);
Assert.assertNotNull(coercing, () -> {
return "coercing can't be null";
});
Assert.assertNotNull(directives, () -> {
return "directives can't be null";
});
this.name = name;
this.description = description;
this.coercing = coercing;
this.definition = definition;
this.directivesHolder = new DirectivesHolder(directives, appliedDirectives);
this.extensionDefinitions = ImmutableList.copyOf(extensionDefinitions);
this.specifiedByUrl = specifiedByUrl;
}
可用的方法为,直接向Spring容器中注入一个GraphQLScalarType对象 比如我向Spring容器中添加了一个Date类型的自定义标量
@Bean
public GraphQLScalarType graphQLDate() {
return GraphQLScalarType
.newScalar()
.name("Date")
.description("Date 类型")
.coercing(new Coercing<Date, String>() {
@Override
public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
return new SimpleDateFormat(DATE_FORMAT_PATTERN_DEFAULT).format((Date) dataFetcherResult);
}
@Override
public Date parseValue(Object input) throws CoercingParseValueException {
if (input instanceof String) {
try {
return new SimpleDateFormat(DATE_FORMAT_PATTERN_DEFAULT).parse((String) input);
} catch (ParseException e) {
throw new CoercingParseValueException(e);
}
}
throw new CoercingParseValueException(
"Expected a 'String' but was '" + Kit.typeName(input) + "'."
);
}
@Override
public Date parseLiteral(Object input) throws CoercingParseLiteralException {
if (!(input instanceof StringValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + input + "'."
);
}
try {
return new SimpleDateFormat(DATE_FORMAT_PATTERN_DEFAULT).parse(((StringValue) input).getValue());
} catch (ParseException e) {
throw new CoercingParseValueException(e);
}
}
})
.build();
}
这样就可以在graphQL的文件中添加Date类型
#scalar定义一个数据模型
scalar Date
type Query{
events1: [Date!]!
}