使用 Pure Code First Hot Chocolate GraphQL 的某个 属性 的日期类型

Date type for a certain property with Pure Code First Hot Chocolate GraphQL

我首先在 Hot Chocolate 中使用纯代码,但我有 dateTime C# 类型,但我遇到了 javascript 中时区转换不正确的问题。所以我希望它输出 Date 而不是 DateTime 对象。现在我正在使用

 SchemaBuilder.New()
 .BindClrType<DateTime, DateType>()

但这是一种非常强力的方法,因为现在我永远无法在 graphQL 中输出 DateTime 类型。

有没有办法在 属性 上放置一个属性或将其设置在某处,以便 class 上的特定 属性 输出为日期而不是日期时间?

是的,有一种非常简单的方法可以达到这个目的。假设你有一些用户 class:

public class User
{
    public int Id { get; set; }

    public DateTime BirthDate { get; set; }
}

为了能够指定 BirthDate 只是一个日期而不是日期时间定义用户 "type metadata" 并将 BirthDate 的 GraphQL 类型指定为 "DateType":

public class UserType : ObjectType<User>
{
    protected override void Configure(IObjectTypeDescriptor<User> descriptor)
    {
        descriptor.Field(t => t.BirthDate).Type<DateType>();
    }
}

并在架构构建中注册该类型:

public void ConfigureServices(IServiceCollection services)
{
        services.AddGraphQL(sp =>
            SchemaBuilder.New()         
                .AddQueryType<Query>()
                .AddType<UserType>()
                .Create());
}

您还可以通过使用 GraphQLType 属性对目标字段进行归属来使用 Pure Code First 方法:

using HotChocolate;

public class User
{
    public int Id { get; set; }

    [GraphQLType(typeof(NonNullType<DateType>))]
    public DateTime BirthDate { get; set; }
}