【问题标题】:GraphQL - Passing an enum value directly to a mutation as an argument?GraphQL - 将枚举值作为参数直接传递给突变?
【发布时间】:2018-05-22 02:59:04
【问题描述】:

给定以下 GraphQL 类型定义:

const typeDefs = `
  enum Action {
    update
    delete
  }    

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

此查询有效:

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

但是这个没有:

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

GraphQL 不支持直接将枚举值作为参数传递吗?

【问题讨论】:

    标签: types enums graphql


    【解决方案1】:

    GraphQL 确实支持将枚举直接作为参数传递;但是,您需要省略值周围的引号才能使其正常工作:

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

    根据spec

    枚举值表示为不带引号的名称(例如 MOBILE_WEB)。

    因此与字符串值不同的是,枚举值不应放在引号内。将它们用于变量时,我们这样做的唯一原因是遵循正确的 JSON 格式。

    【讨论】:

    • 只是我,还是使用枚举很难通过变量对象传递参数?
    【解决方案2】:

    在后端定义的枚举是:

    enum Gender {
      MALE
      FEMALE
    }
    

    我将 Vue 用于前端,因此可以像这样将数据从 Vue 传递给突变。 我在组件的本地状态中将性别定义为字符串:

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

    来自 Vue 的方法是:

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

    在 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
        }
    }
    `
    

    使用突变中定义的枚举变量名并将其发送到 Graphql,就像我使用的性别一样 $gender: Gender! 在 gql 突变中。您不必担心以枚举形式发送数据,只需将其作为字符串发送,否则您将不得不面对 JSON 错误,Graphql 将处理您作为字符串发送的值(例如 'MALE ' 或 'FEMALE') 只是不要忘记提及性别是 gql 突变中的性别类型(即枚举),就像我在上面所做的那样。

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2012-04-18
      • 2022-08-19
      • 1970-01-01
      • 2017-09-22
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多