c# - 如何在 .NET 中使用 Hot Chocolate 扩展 GraphQL 自省(introspection)类型

标签 c# .net .net-core graphql hotchocolate

就我而言,我想扩展 __EnumValue自省(introspection)类型本质上携带有关枚举值的附加信息。如何向内省(introspection)添加其他字段。

最佳答案

在 Hot Chocolate 中,每种类型都可以扩展。在上面的例子中,我们想要扩展一个对象类型,它是 GraphQL 中的一种输出类型。
为此,我们创建了一个简单的类并使用 ExtendObjectTypeAttribute 注释该类。 .

[ExtendObjectType("__EnumValue")]
public class EnumTypeExtension
{
    public string GetAdditionalInfo([Parent] IEnumValue enumValue) =>
        enumValue.ContextData["additionalInfo"].ToString();
}
请注意,您可以注入(inject)原始类型具有的任何信息。在本例中,我们注入(inject) __EnumValue 的运行时值。键入以公开其他信息。
以上转换为以下 SDL:
extend type __EnumValue {
  additionalInfo: String!
}
最后,我们需要在模式中注册我们的类型扩展。
services
    .AddGraphQL()
    .AddQueryType<QueryType>()
    .AddTypeExtension<EnumTypeExtension>();
之后,我们可以像下面这样查询:
query {
  __type(name: "MyEnum") {
    enumValues {
       additionalInfo
    }
  }
}
对此有一点警告,随着规范的推进,它可能会在自省(introspection)中引入可能与您的字段发生冲突的新字段。因此,实际引入一个字段 extensions 是一个很好的做法。并将您的扩展字段放在那里。这遵循了 GraphQL 中请求和响应的扩展方式。
type EnumValueExtensions {
  additionalInfo: String!
}

extend type __EnumValue {
  extensions: EnumValueExtensions!
}

关于c# - 如何在 .NET 中使用 Hot Chocolate 扩展 GraphQL 自省(introspection)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66024999/

相关文章:

c# - 从数据对象转换为业务对象。最佳实践

c# - 如何在 C# 和 MS SQL 中向参数化查询添加 "select all"值

c# - 我可以将 WCF Web 服务限制为仅来自特定域的调用吗?

C# 异步 Ping : not work from a Threading. 定时器

c# - Int16 - .net 中的字节容量?

c# - 获取线程 ID

c# - 使用 .NET 中的 pHash

c# - 程序不包含适合入口点异步等待的静态 'main' 方法

c# - 在 dotnet 核心 "the configured user limit (128) on the number of inotify instances has been reached"中读取 json 文件时出错

request - 在 WebApi Core ConfigureServices 中访问 services.AddScoped 中的请求 header ?