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.
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.
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.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With