【问题标题】:Is there a way to ignore all fields by default on a GraphQL type and only add the wanted field?有没有办法默认忽略 GraphQL 类型上的所有字段,只添加想要的字段?
【发布时间】:2021-01-18 11:08:05
【问题描述】:

有没有办法默认忽略 GraphQL 类型上的所有字段,只添加想要的字段?

Hot Chocolate 自动从 C# 类型推断出 GraphQL 类型成员。

这意味着下面的代码...

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

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

将产生以下 GraphQL 类型:

type Foo {
  bar: String!
  baz: String
}

在我的用例中,我想更改此行为并明确定义在 GraphQL 类型中使用我的 C# 类型的哪个类型成员。

【问题讨论】:

    标签: asp.net .net graphql hotchocolate


    【解决方案1】:

    Hot Chocolate 允许您反转每种类型或整个架构的行为。

    要声明一种特定类型的所有字段,请显式执行以下操作:

    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!
      baz: String
    }
    

    如果您想在架构中的所有类型上显式声明字段,您可以设置以下选项:

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

    如果您全局设置它,您可以始终按类型覆盖它,这意味着您可以在这种情况下定义以按类型隐式绑定成员。

    【讨论】:

    • 有没有办法默认为过滤和排序的显式绑定行为?类似.AddFiltering(c =&gt; c.DefaultBindingBehavior = BindingBehavior.Explicit)
    • 为了完整起见,还有一个反向选项(默认):descriptor.Field(...).Ignore()
    • 小评论,我认为答案的架构不正确。 “baz”不应该在那里,因为它没有明确定义。读起来有点迷惑 ;-)
    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多