【问题标题】:Custom graphQL scalar LocalDateTime自定义 graphQL 标量 LocalDateTime
【发布时间】:2020-08-03 02:30:31
【问题描述】:

我正在使用 graphql-spring-boot-starter 创建 GraphQL API。 AFAIK 不存在默认的 LocalDateTime 标量,所以我想创建我的自定义。我试着这样做:

 @Bean
public GraphQLScalarType dateTimeType() {
    return new GraphQLScalarType("LocalDateTime", "DataTime scalar", new Coercing() {
        @Override
        public String serialize(Object input) {
            LocalDateTime date = (LocalDateTime) input;
            return   date.toString();
        }

        @Override
        public LocalDateTime parseValue(Object input) {
            return LocalDateTime.parse((String) input);
        }

        @Override
        public LocalDateTime parseLiteral(Object input) {
            return LocalDateTime.parse((String) input);
        }
    });

}

我遇到了异常:

java.lang.IllegalArgumentException:无法构造java.time.LocalDateTime 的实例(没有创建者,如默认构造,存在):无法从对象值反序列化(没有基于委托或属性的创建者)

您能告诉我如何在我的项目中处理 dateTime 吗?

【问题讨论】:

  • 这和 Elasticsearch 有什么关系?

标签: spring-boot graphql-java


【解决方案1】:

我认为在为 SchemaParserOptions 提供调整后的映射器配置后,它可以工作:

    @Bean
public SchemaParserOptions schemaParserOptions(){
   return SchemaParserOptions.newOptions().objectMapperConfigurer((mapper, context) -> {
        mapper.registerModule(new JavaTimeModule());
    }).build();
}

GraphQL 使用自己的 objectmapper,因此您必须在其上注册 JavaTimeModule。

更多信息,例如这里:github.com/graphql-java-kickstart/graphql-spring-boot/issues/32

感谢@Florian Schechner @ Dr.Oste

【讨论】:

【解决方案2】:

这是我在项目中为传递日期和时间所做的操作

@Component
public class DateScalarType extends GraphQLScalarType {
public DateScalarType() {
    super("Date", "Date TIME", new Coercing() {
        @Override
        public Object serialize(Object o) throws CoercingSerializeException {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
            return formatter.format((Date)o);
        }

        @Override
        public Object parseValue(Object o) throws CoercingParseValueException {
            return o;
        }

        @Override
        public Object parseLiteral(Object o) throws CoercingParseLiteralException {
            if (o==null){
                return null;
            }
            return o.toString();
        }
    });
}}

在graphqls文件中

scalar Date

type example {
creationDate:Date! }

【讨论】:

猜你喜欢
  • 2018-05-29
  • 2020-10-21
  • 2018-02-12
  • 2022-08-05
  • 2020-08-03
  • 2018-06-30
  • 2019-10-12
  • 1970-01-01
  • 2019-06-24
相关资源
最近更新 更多