GraphQL-SPQR中的自定义标量类型 [英] Custom Scalar Type in graphql-spqr

查看:52
本文介绍了GraphQL-SPQR中的自定义标量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I GraphQL-SPQR,java.util.Date定义为Scalar。是否可以覆盖java.util.Date的序列化/反序列化以获得日期的不同字符串表示形式?

answer中提到的ScalarStrategy已从最新版本中删除。

public class Order {

    private String id;
    private Date orderDate; //GraphQLScalarType "Date"

    public Order() {
    }

    public Order(String id, String bookId, Date orderDate) {
        this.id = id;
        this.orderDate = orderDate;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }
}

图形QL响应:

{
  "data": {
    "createOrder": {
      "id": "74e4816c-f850-4d63-9855-e4601fa125f4",
      "orderDate": "2019-05-26T08:25:01.349Z", // --> 2019-05-26
    }
  }
}

推荐答案

ScalarStrategy不是实现您想要的目标的正确方式。当您要更改Java类型映射到GraphQL的方式时,通常需要提供新的(或自定义现有的)TypeMapper

查看现有的Date标量实现,并以类似的方式实现您自己的。然后实现一个自定义TypeMapper,它只是始终从toGraphQLTypetoGraphQLInputType方法返回该标量的静电实例。

public class CustomTypeMapper implements TypeMapper {

    private static final GraphQLScalarType GraphQLCustomDate = ...;

    @Override
    public GraphQLOutputType toGraphQLType(...) {
        return GraphQLCustomDate;
    }

    @Override
    public GraphQLInputType toGraphQLInputType(...) {
        return GraphQLCustomDate;
    }

    @Override
    public boolean supports(AnnotatedType type) {
        return type.getType() == Date.class; // This mapper only deals with Date
    }
}

若要注册它,请调用generator.withTypeMappers(new CustomTypeMapper()

也就是说,因为您只想切断时间部分,所以理想情况下在这里使用LocalDate。您可以通过注册TypeAdapter(它只是一个映射器+转换器)来透明地让SPQR实现这一点,但是在您的情况下,如上所述的简单映射器是一个更有效的解决方案。如果您仍然决定采用适配器的方式,您可以继承AbstractTypeAdapter<Date, LocalDate>并实现转换逻辑(应该很简单)。通过generator.withTypeAdapters注册,或将其分别注册为映射器和转换器。

这篇关于GraphQL-SPQR中的自定义标量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆