GraphQL添加自定义标量

继承GraphQLScalarType类,然后重写父类的构造器,传入三个参数。这个方法已经过时了,最新的构造器需要传入5个参数,都有非空校验

private GraphQLScalarType(String name, String description, Coercing coercing, List directives, List appliedDirectives, ScalarTypeDefinition definition, List 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类型的自定义标量
@Beanpublic GraphQLScalarType graphQLDate() {return GraphQLScalarType.newScalar().name("Date").description("Date 类型").coercing(new Coercing() {@Overridepublic String serialize(Object dataFetcherResult) throws CoercingSerializeException {return new SimpleDateFormat(DATE_FORMAT_PATTERN_DEFAULT).format((Date) dataFetcherResult);}@Overridepublic 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) + "'.");}@Overridepublic 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 Datetype Query{events1: [Date!]!
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部