Michael Ingmar Staib
Michael Ingmar Staib

Reputation: 1952

How can I extend the GraphQL introspection types with Hot Chocolate in .NET

In my case I want to extend the __EnumValue introspection type to essentially carry additional information about the enum value. How can I add additional fields to the introspection.

Upvotes: 10

Views: 2261

Answers (1)

Michael Ingmar Staib
Michael Ingmar Staib

Reputation: 1952

In Hot Chocolate, every type can be extended. In the above case, we want to extend an object type, which is an output type in GraphQL.

In order to do that we create a simple class and annotate that class with the ExtendObjectTypeAttribute.

[ExtendObjectType("__EnumValue")]
public class EnumTypeExtension
{
    public string GetAdditionalInfo([Parent] IEnumValue enumValue) =>
        enumValue.ContextData["additionalInfo"].ToString();
}

Note that you can inject any information that the original type has. In this instance, we inject the runtime value of the __EnumValue type to expose additional information.

The above translates to the following SDL:

extend type __EnumValue {
  additionalInfo: String!
}

Lastly, we need to register our type extension with the schema.

services
    .AddGraphQL()
    .AddQueryType<QueryType>()
    .AddTypeExtension<EnumTypeExtension>();

After that, we can query this like the following:

query {
  __type(name: "MyEnum") {
    enumValues {
       additionalInfo
    }
  }
}

Just a little warning on this, as the spec advances, it could introduce new fields on the introspection that might collide with your fields. So, it is a good practice to actually introduce a field extensions and put your extended fields on there. This follows the way the request and response in GraphQL are extended.

type EnumValueExtensions {
  additionalInfo: String!
}

extend type __EnumValue {
  extensions: EnumValueExtensions!
}

Upvotes: 13

Related Questions