Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 539
Michael Ingmar Staib Avatar asked Feb 03 '21 09:02

Michael Ingmar Staib


People also ask

What is extend type in GraphQL?

Starting with the June2018 stable version of the GraphQL spec, an Object type can extend another Object type: Object type extensions are used to represent a type which has been extended from some original type. For example, this might be used to represent local data.

What is hot chocolate GraphQL?

Hot Chocolate is an open-source GraphQL server for the Microsoft . NET platform that is compliant with the newest GraphQL October 2021 spec + Drafts, which makes Hot Chocolate compatible to all GraphQL compliant clients like Strawberry Shake, Relay, Apollo Client, and various other clients and tools.


1 Answers

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!
}
like image 121
Michael Ingmar Staib Avatar answered Sep 23 '22 00:09

Michael Ingmar Staib