Query for enum value in GraphQL
Asked Answered
S

1

12

Suppose I have a model like this

class Order(models.Model):
    STATES = [
        (1, 'Initiate'),
        (2, "Brief"),
        (3, "Planning"),
        (4, "Price Negotiate"),
        (5, "Executing"),
        (6, "Pending"),
        (7, "Completed"),
        (8, "Canceled"),
        (9, "Failed"),
        (10, "Paid"),
    ]

    state = models.PositiveSmallIntegerField(
        choices=STATES,
        default=1
    )

When I pair this model with its Graphene object type companion

class OrderNode(graphene_django.DjangoObjectType):
    class Meta:
        model = Order
        interfaces = (relay.Node,)

An enum type with name OrderState! is created.

I am concerned with

  1. How can I query for the enums
  2. How can I manage enums in React with Apollo client

For the first question, I have this query

{
  customer(id: "Q3VzdG9tZXJOb2RlOjE=") {
    name
    orders {
      edges {
        node {
          state
        }
      }
    }
  }
}

It gives me a weird state value like A_1 and A_2. I was expecting it to give me some meaningful value like "Initiate". How can I get the value of the kv pair enum?

For the second question, if I want to present to user a list of possible value for this enum, how can I do so?

Simaroubaceous answered 17/11, 2016 at 11:30 Comment(1)
I also have the similar issue. Whenever I query for a field with choices it returns capital-case value. But when I try to filter query using that value I get error \"Select a valid choice. TEST_VALUE is not one of the available choices.\", \"code\": \"invalid_choice\". It makes no sense.Nutrition
S
12

I found a solution, though I wonder if it is the best one. In addition to the query that has enum values, I included this query

query {
    # previous queries
    __type(name: "OrderState") {
       states: enumValues {
           name
           description
       }
    }
}

It pulls all possible key-value pairs for the OrderState enum. I then can use this as a dictionary to lookup enum values.

I feel that this approach is still too manual, but there are no examples that make a query for enum values. They just stopped at describing what an enum is, and how to declare one.

Simaroubaceous answered 17/11, 2016 at 13:32 Comment(1)
Any update on making this more automagic? It seems ridiculous to both a) statically request each of these types in a query or b) dynamically fire a ton of queries for all required typesHarms

© 2022 - 2024 — McMap. All rights reserved.