GraphQL - Passing an enum value directly to a mutation as an argument?
Asked Answered
G

2

23

Given the following GraphQL type definition:

const typeDefs = `
  enum Action {
    update
    delete
  }    

  type Mutation {
    doSomething(action: Action)
  }
`;

This query works:

const query = `
  mutation($action: Action) {
    doSomething(action: $action)
  }
`
const variables = { action: "update" }

But this one does not:

const query = `
  mutation {
    doSomething(action: "update")
  }
`

Does GraphQL not support passing an enum value directly as an argument?

Gesture answered 7/12, 2017 at 22:5 Comment(0)
F
45

GraphQL does support passing the enum directly as an argument; however, you'll need to omit the quotation marks around the value to get it to work:

const query = `
  mutation {
    doSomething(action: update)
  }
`

According to the spec:

Enum values are represented as unquoted names (ex. MOBILE_WEB).

So unlike a string value, an enum value should not be put inside quotation marks. The only reason we do so when using them for variables is to follow proper JSON formatting.

Frangipani answered 8/12, 2017 at 3:44 Comment(1)
Is it just me, or does using an enum make it difficult to pass arguments in via a variables object?Gooseflesh
U
4

enum defined in backend is:

enum Gender {
  MALE
  FEMALE
}

I am using Vue for frontend so passing data to the mutation from Vue can be done like this. I have defined gender as a string in my local state of the component as:

data(){
  return {
     gender: ''
  }
}

The method from Vue is:

async handleEditProfile () {
      const response = await this.$apollo.mutate({
        query: EDIT_PROFILE,
        variables: {
          nameAsInPan: this.nameAsInPan,
          gender: this.gender,
          dateOfBirth: this.dateOfBirth
        }
      })
    }

mutation used above EDIT_PROFILE:

gql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {
    editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){
      id
      email
      phone
      firstName
      lastName
      nameAsInPan
      gender
      dateOfBirth
    }
}
`

use the enum variable name as defined in the mutation and send it to Graphql, like I have used gender As $gender: Gender! in gql mutation.You don't have to worry about sending data as enum, just send it as String otherwise you will have to face JSON error, Graphql will take care of the value you send as a string (like 'MALE' or 'FEMALE') just don't forget to mention that gender is type of Gender(which is enum) in gql mutation as I did above.

Unbend answered 11/12, 2019 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.