How to define enums for key values in graphql?

by lindsey.homenick , in category: Javascript , 7 months ago

How to define enums for key values in graphql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 7 months ago

@lindsey.homenick 

In GraphQL, enums (short for enumerations) are a way to define a specific set of values that a field can have. To define enums for key values in GraphQL, you can follow these steps:

  1. Define the Enum type in your GraphQL schema:
1
2
3
4
enum Status {
  ACTIVE
  INACTIVE
}


  1. Use the Enum type as a field type in your GraphQL schema:
1
2
3
4
5
type User {
  id: ID!
  name: String!
  status: Status!
}


  1. Use the Enum values when querying data:
1
2
3
4
5
6
7
query {
  user(id: "123") {
    id
    name
    status
  }
}


  1. When defining a mutation, use the Enum type for input:
1
2
3
4
5
6
7
8
input CreateUserInput {
  name: String!
  status: Status!
}

type Mutation {
  createUser(input: CreateUserInput!): User!
}


  1. Use the Enum values when creating or updating data:
1
2
3
4
5
6
7
mutation {
  createUser(input: { name: "Alice", status: ACTIVE }) {
    id
    name
    status
  }
}


By defining enums for key values in GraphQL, you can ensure that only certain predefined values are allowed for specific fields, making your API more predictable and robust.