如何在GraphQL模式中指定DateTime ?



我正在为我的项目构建我的GraphQL模式,我的一个模型具有DateTime格式。

我如何在我的GraphQL模式上写出日期格式?

我尝试了DateTime或Date,但没有显示。

这是模型:

public Integer Id;
public String name;
public String description;
public LocalDate birthDate;

这是我的GraphQL模式:

type Pet {
id: ID!
name: String!
description: String
birthDate: DateTime
} 

但是它说:

未知类型日期时间

为框架不能识别的类型创建一个自定义标量。

我不确定您使用的是哪种基于graphql-java的框架。我假设您使用的是Spring团队提供的GraphQL官方Spring。

  1. 创建一个自定义标量,例如my LocalDateTime标量

    LocalDateTimeScalar实现了Coercing<LocalDateTime,>{@Overridepublic String serialize(Object dataFetcherResult)抛出CoercingSerializeException {if (datafetcherresultinstanceof LocalDateTime) {return ((LocalDateTime) dataFetcherResult).format(DateTimeFormatter.ISO_DATE_TIME);} else {抛出新的CoercingSerializeException("无效的日期时间");}}

    @Override
    public LocalDateTime parseValue(Object input) throws CoercingParseValueException {
    return LocalDateTime.parse(input.toString(), DateTimeFormatter.ISO_DATE_TIME);
    }
    @Override
    public LocalDateTime parseLiteral(Object input) throws CoercingParseLiteralException {
    if (input instanceof StringValue) {
    return LocalDateTime.parse(((StringValue) input).getValue(), DateTimeFormatter.ISO_DATE_TIME);
    }
    throw new CoercingParseLiteralException("Value is not a valid ISO date time");
    }
    

    }

  2. 在您的自定义RuntimeWiringbean中注册它,点击这里。

    public class Scalars {
    public static GraphQLScalarType localDateTimeType() {
    return GraphQLScalarType.newScalar()
    .name("LocalDateTime")
    .description("LocalDateTime type")
    .coercing(new LocalDateTimeScalar())
    .build();
    }
    }
    
    @Component
    @RequiredArgsConstructor
    public class PostsRuntimeWiring implements RuntimeWiringConfigurer {
    private final DataFetchers dataFetchers;
    @Override
    public void configure(RuntimeWiring.Builder builder) {
    builder
    //...
    .scalar(Scalars.localDateTimeType())
    //...
    .build();
    }
    }
    

如果你在其他基于GraphQL - Java的框架(GraphQL Java, GraphQL Java Kickstart, GraphQL Kotlin, GraphQL SPQR, Netflix DGS等)和spring集成中使用标量,请查看我的spring GraphQL示例。后端原理是类似的,只是配置不同。

最新更新