Search code examples
asp.net.netgraphqlhotchocolate

Is there a way to ignore all fields by default on a GraphQL type and only add the wanted field?


Is there a way to ignore all fields by default on a GraphQL type and only add the wanted field?

Hot Chocolate infers GraphQL type members form the C# type automatically.

This means that the following code ...

public class Foo
{
    public string Bar { get; set; }

    public string? Baz { get; set; }
}
public class FooType : ObjectType<Foo>
{
}

will result in the following GraphQL type:

type Foo {
  bar: String!
  baz: String
}

In my use-case I want to change this behavior and define explicitly which type member of my C# type is used in the GraphQL type.


Solution

  • Hot Chocolate allows you to reverse the behavior per type or for the whole schema.

    To declare all fields on one specific type, explicitly do the following:

    public class FooType : ObjectType<Foo>
    {
        protected override void Configure(IObjectTypeDescriptor<Person> descriptor)
        {
             // this defines that fields shall only be defined explicitly
             descriptor.BindFieldsExplicitly();
    
             // now declare the fields that you want to define.
             descriptor.Field(t => t.Bar);    
        }
    }
    
    type Foo {
      bar: String!
    }
    

    If you want to declare fields explicitly on all types in your schema, you can set the following option:

    services
        .AddGraphQLServer()
        .AddQueryType<Query>()
        // this option will, by default, define that you want to declare everything explicitly.
        .ModifyOptions(c => c.DefaultBindingBehavior = BindingBehavior.Explicit);
    

    If you set it globally, you can override it always per type, meaning you can define in that case to bind members implicitly on a by type basis.