【问题标题】:GraphQL SPQR Unable to serialize ZonedDateTime as expectedGraphQL SPQR 无法按预期序列化 ZonedDateTime
【发布时间】:2020-02-11 12:14:57
【问题描述】:

我在 graphql-spqr-0.10.0 上并使用代码优先方法,这是客户可以查询的示例类型。

@GraphQLType(name = "Activity", description = "Some activity")
public class SomeActivity {

  @GraphQLQuery(description = "Unique id")
  private @NotNull Long id = null;

  @GraphQLQuery(description = "Activity name")
  private @NotNull String name = null;

  @GraphQLScalar @GraphQLQuery(description = "Activity start date time")
  private @NotNull ZonedDateTime startTime = null;

  ...
}

我在类路径中有 graphql-java-extended-scalars(1.0 版),我在其中一个线程中读到,我可以用 @GraphQLScalar 标记 ZonedDateTime 字段,以便用 graphql.scalars.datetime.DateTimeScalar 对其进行序列化并生成ISO_OFFSET_DATE_TIME 日期格式。

这是我不认为是所需的 ISO 格式“startTime”的实际响应格式:“2017-12-29T16:59:57-06:00[America/Chicago]”

这是使用扩展标量的正确方法吗?

【问题讨论】:

    标签: graphql-java graphql-spqr


    【解决方案1】:

    你不应该在这里使用@GraphQLScalar。该注释用于强制将复杂类型视为动态结构的标量。 ZonedDateTime 已经被 SPQR 视为标量,并具有正确实施的强制,因此添加 @GraphQLScalar 会搞砸。

    此外,您并不需要扩展标量库,除非您出于某种原因更喜欢该实现而不是 SPQR(我认为它们实际上是等效的)。在这种情况下,您使用自定义映射器的方法是正确的。

    【讨论】:

      【解决方案2】:

      我最终通过定义如下所示的自定义 TypeMapper 类解决了这个问题。虽然我不知道这是否是解决这个问题的正确方法。然后用 GraphQLSchemaGenerator().withTypeMappers() 注册一个新的 ZonedDateTimeTypeMapper 实例

      public class ZonedDateTimeTypeMapper implements TypeMapper {
      
          private static final GraphQLScalarType type = new graphql.scalars.datetime.DateTimeScalar();
      
          @Override
          public boolean supports(AnnotatedType type) {
              return type.getType() == ZonedDateTime.class;
          }
      
          @Override
          public GraphQLInputType toGraphQLInputType(AnnotatedType javaType, OperationMapper operationMapper,
                  Set<Class<? extends TypeMapper>> mappersToSkip, BuildContext buildContext) {
              return type;
          }
      
          @Override
          public GraphQLOutputType toGraphQLType(AnnotatedType javaType, OperationMapper operationMapper,
                  Set<Class<? extends TypeMapper>> mappersToSkip, BuildContext buildContext) {
              return type;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-12-24
        • 2019-11-09
        • 2016-04-25
        • 2013-05-01
        • 2020-02-28
        • 2017-05-05
        • 2018-10-07
        • 2022-12-12
        • 1970-01-01
        相关资源
        最近更新 更多