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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x