DEV Community

Cover image for Enums in GraphQL
Doaa Mahely
Doaa Mahely

Posted on

Enums in GraphQL

What are enums?

Enums or enumerations are a data type in programming languages. Enums hold named variables, which is just a fancy way of saying that they hold a number of predefined values. Enums also help us by providing additional input validation.

When should I use an enum?

Typically, enums are used when you have a property that can only have a predefined set of values. For example, a student's attendance for the day. The value of attendance can only ever be present, absent, or late. Another example is the delivery status of a message. Possible values are sent, delivered and read.

How to define an enum in GraphQL schema?

So now we've decided that we want our property to be of type enum. How can we define that in our schema? Simply:

enum messagesDeliveryStatus {
    sent
    delivered
    read
}
Enter fullscreen mode Exit fullscreen mode

Example

type RootQuery {
     messages(deliveryStatus: messagesDeliveryStatus): [Message]
}

type Message {
     id: ID
     message: String
     deliveryStatus: messageDeliveryStatus
     sentAt: String
}
Enter fullscreen mode Exit fullscreen mode

This simple schema does two things. It defines an object type called Message which has some properties, specifically one property called deliveryStatus, which is of type messagesDeliveryStatus that we defined above.

It also defines a query in root called messages, which returns all the messages we have, and we can filter them by delivery status.

query {
     messages(deliveryStatus: "read") {
        message
        type
        deliveryStatus
        sentAt
   }
}
Enter fullscreen mode Exit fullscreen mode

Oops, running this query causes an error. The error message you'll see is:
"message": "Expected type messagesDeliveryStatus, found \"read\". Did you mean the enum value read?",

Now I faced this error message more than once, and when you're in a hurry or frustrated, it's likely the error message won't make a lot of sense. You're telling me you're expecting the value I'm passing?

The mistake we made here is that we passed the value read as a string. What we need to do is remove the double quotes around it. Let's try that again:

query {
     messages(deliveryStatus: read) {
        message
        type
        deliveryStatus
        sentAt
   }
}
Enter fullscreen mode Exit fullscreen mode

And now we're getting our expected results: only messages that were read!

Thank you for reading. Let me know how I can make this article better. Until next time 👋

Cover photo by Kari Shea on Unsplash

Top comments (1)

Collapse
 
mysticdakra profile image
Dakra-Mystic

How do you pass in multiple enums? If possible I cannot seem to pass in more than one option.