Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for enum value in GraphQL

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?

like image 893
Khanetor Avatar asked Nov 17 '16 11:11

Khanetor


1 Answers

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.

like image 65
Khanetor Avatar answered Sep 21 '22 12:09

Khanetor