Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting .NET Enum to GraphQL EnumerationGraphType

How do I convert an enum to the EnumerationGraphType that GraphQL uses? Here is an example to illustrate what I'm talking about:

public enum MeetingStatusType
{
    Tentative,
    Unconfirmed,
    Confirmed,
}
public class MeetingDto
{
    public string Id { get; set; }
    public string Name { get; set; }
    public MeetingStatusType Status { get; set; }
}
public class MeetingStatusEnumType : EnumerationGraphType<MeetingStatusType>
{
    public MeetingStatusEnumType()
    {
        Name = "MeetingStatusType";
    }
}
public class MeetingType : ObjectGraphType<MeetingDto>
{
    public MeetingType()
    {
        Field(m => m.Id);
        Field(m => m.Name, nullable: true);
        Field<MeetingStatusEnumType>(m => m.Status); // Fails here
     }
}

Obviously this doesn't work because there's no implicit conversion from MeetingStatusType to MeetingStatusEnumType. In the documentation, the models that they were mapping would rely directly on MeetingStatusEnumType, but it doesn't seem good to introduce the dependency on GraphQL on something like your domain types and objects. I feel like I'm missing a painfully easy way to register this field, but I can't figure it out for the life of me. Any help would be greatly appreciated!

like image 860
Daric Avatar asked May 08 '19 02:05

Daric


People also ask

Can you use enums in GraphQL?

Enums limit the range of a variable's values to a set of predefined constants, which makes it easier to document intent. GraphQL also has enum type support, so TypeGraphQL allows us to use TypeScript enums in our GraphQL schema.

How do you pass enum in a GraphQL mutation?

You don't have to worry about sending data as enum, just send it as String otherwise you will have to face JSON error, Graphql will take care of the value you send as a string (like 'MALE' or 'FEMALE') just don't forget to mention that gender is type of Gender(which is enum) in gql mutation as I did above.

What is enum GraphQL?

An enum is a GraphQL schema type that represents a predefined list of possible values. For example, in Airlock, listings can be a certain type of location: a spaceship, house, campsite, apartment, or room. We represent this in our schema through a locationType field.


1 Answers

Looks like I should not have been trying to use the expression overload for mapping the fields. Switching it out to be the following instead seems to have solved the issue:

Field(e => e.Id);
Field(e => e.Name, nullable: true);
Field<MeetingStatusEnumType>("meetingStatus", resolve: e => e.Source.Status);
like image 191
Daric Avatar answered Oct 06 '22 01:10

Daric