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

Viewed 2096

I am using pure code first with Hot Chocolate but I have dateTime C# type and I am having problems with the timezone getting converted incorrectly in javascript. So I would like it to output a Date instead of a DateTime object. For now I am using

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

but this is a very brute force approach as now I can never output a DateTime type in graphQL.

Is there way to put an attribute on the property or set it up somewhere so that a specific property on a class is output as a Date instead of DateTime?

2 Answers

You can also use Pure Code First approach by attributing target field with GraphQLType attribute:

using HotChocolate;

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

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

Yes, there's a pretty straightforward way of reaching that. Suppose you have some User class:

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

    public DateTime BirthDate { get; set; }
}

To be able to specify that BirthDate is just a date but not datetime define the User "type metadata" and specify the GraphQL type of BirthDate as "DateType":

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

and register that type on schema building:

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