FredericBirke
FredericBirke

Reputation: 1242

How can you control the serialization of Enum values in HotChocolate?

HotChocolate serializes enum values in all upper snail case, which leads to being the enum value FooBar being inferred as FOO_BAR by Hot Chocolate, but value.ToString() and Enum.GetName(value) gives FooBar, and Hot Chocolate seems to ignore [EnumMember(Value = "FooBar")].

How can I change the serialization to any way I'd like?

Upvotes: 5

Views: 4055

Answers (2)

vivek86
vivek86

Reputation: 753

If you would like to do some custom serialization and deserialization of enum values, like using Description instead of the Enum Value then do the following:

public enum Colour
{
  [Description("Red")] RedColour,
  [Description("Blue")] BlueColour,
}

public class ColourEnumType : EnumType<Colour>
{
    protected override void Configure(IEnumTypeDescriptor<Colour> descriptor)
    {
      descriptor.Name("CustomColour").Description("Custom colour enum").EnumTypeSerialization();
    }
}

internal static void EnumTypeSerialization<TEnum>(this IEnumTypeDescriptor<TEnum> descriptor)
        where TEnum : struct, Enum
{
    var enumValues = Enum.GetValues<TEnum>();
    foreach (var value in enumValues)
        descriptor.Value(value).Name(value.GetDescription());
}

You can now register the ColourEnumType in the service collection and HotChocolate will then correctly return the enum description instead of the value.

serviceCollection.AddGraphQLServer()
                 .AddQueryType<QueryType>()
                 .AddType<ColourEnumType>()

I have tested this on HotChocolate v13.0.5 and you need to write the code for the GetDescription() method.

One last thing to remember though is to make sure that your enum description values are GraphQL compliant. If they arent, then you need to either change your descriptions or sanitize your results during the serialization process. If not, it will cause HotChocolate to crash with errors that will be very hard to debug.

Upvotes: 0

FredericBirke
FredericBirke

Reputation: 1242

HotChocolate server v11 follows the spec recommendation which defaults to enum values being serialized as UPPER_SNAIL_CASE per default.

You can change this like this:

    builder
        .AddConvention<INamingConventions>(new YourNamingConvention())

    public class YourNamingConvention
        : DefaultNamingConventions
    {
        public override NameString GetEnumValueName(object value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            return value.ToString().ToUpperInvariant(); // change this to whatever you like
        }
    }

Upvotes: 12

Related Questions