Ahtisham
Ahtisham

Reputation: 10116

Unable to return Enum in GraphQL got Unhashable type: 'EnumMeta'

What I am trying to do

I am trying to return Enum values with their names so if I run query:

{
  getFruits {
    fruits
  }
}

I want the output:

{
  data: {
     fruits: [
         {APPLE: 1},
         {ORANGE: 2},
         {MANGO: 3}
     ]    
  }
}

But I get an error:

{
  "errors": [
    {
      "message": "unhashable type: 'EnumMeta'",
      "locations": [
        {
          "line": 20,
          "column": 3
        }
      ],
      "path": [
        "getFruits"
      ]
    }
  ],
  "data": {
    "getFruits": null
  }
}

I did look at the docs but it doesn't help.

What is the purpose of returning Enum ?

To display valid choices that can be used as arguments for subsequent queries.

My Code:

Type:

class EnumType(graphene.Enum):
    APPLE = 1
    ORANGE = 2
    MANGO = 3


class FruitType(graphene.ObjectType):
    fruits = graphene.List(EnumType)

Resolver:

class MyQuery(graphene.ObjectType):
    get_fruits = graphene.Field(FruitType)

    def resolve_get_fruits(self, info):
        fruits = [
            {EnumType.APPLE: 1},
            {EnumType.ORANGE: 2},
            {EnumType.MANGO: 3}
        ]
        return FruitType(
            fruits=fruits
        )

I don't know if that is the right way to do it since I am new to GraphQL in general.

Upvotes: 2

Views: 617

Answers (1)

Giannis
Giannis

Reputation: 5526

This is an old question, but I think you need to think better about your usecase. Why do you need to return the valid types of Enums ? If its a Enum, then the values are static, therefore the correct values can be described by the schema, there is no reason to return them via a query. If the values are not fixed, then its not an Enum anymore as the whole point of enums are to be static. In that case you can just return a dictionary or a list of strings (assuming the client only cares about the keys, not what values they represent on your service) .

Upvotes: 1

Related Questions