graphql - 如何在 apollo-client 中使用枚举?

标签 graphql apollo apollo-client vue-apollo

OrderTypesEnum.gql 中定义的枚举

enum OrderTypes {
  full_buy
  pink_buy
}

导入 OrderTypesEnum.gql 文件
import OrderTypes from '@/graphql/OrderTypesEnum.gql'`

但是,如何在代码中获取枚举?

我用 OrderTypes.full_buy得到一些错误:
   self.$apollo.mutate({
        mutation: createOrder,
        variables: {
          subjectId: self.subject.id,
          types: OrderTypes.full_buy
        }
      })
Mutation createOrderMutation error: Invariant Violation: Schema type definitions not allowed in queries. Found: "EnumTypeDefinition"

OrderTypes 类型枚举的检查

enter image description here

最佳答案

先决条件:
我们必须在我们的 GraphQL 模式中定义 (服务器端,不需要客户端配置)
假设我们已经定义:

enum SomeEnumType {
    OPTION1,
    OPTION2,
    OPTION3
}
我们还必须以适当的方式配置我们的 Apollo 客户端,并将其与 GraphQL API 连接起来。
然后在客户端:
export const OUR_MUTATION = gql`
    mutation ourMutation($foo: SomeEnumType){
        ourMutation(foo: $foo){
            bar
        }
    }    
`
只有这样做,您才能在查询或突变中将枚举作为变量传递。例如使用 useMutation 钩子(Hook),我们现在可以进行如下变异:
const [ourMutation] = useMutation(OUR_MUTATION, {
        variables: {
            foo: "OPTION2"
        },
由于 gql 标签中的类型定义与 Schema 中的定义相同,GraphQL 将我们的变量识别为枚举类型,尽管我们将其作为字符串给出。
如果我们想使用 typescript 枚举将枚举传递给我们的变量,我们可以这样做:
enum SomeEnumType {
    OPTION1 = 0,
    OPTION2 = 1,
    OPTION3 = 2
}

const [ourMutation] = useMutation(OUR_MUTATION, {
        variables: {
            foo: SomeEnumType[SomeEnumType.OPTION1]
        },

关于graphql - 如何在 apollo-client 中使用枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57998188/

相关文章:

javascript - String 类型的 $lastName 用于需要 String 类型的位置

express - Apollo Server Express : Request entity too large

vue.js - 从 Vue 3 组合 api 中的函数内部返回 Apollo useQuery 结果

Azure Cosmos db 和函数 javascript sdk - 如何异步读取文档?

javascript - [GraphQL 错误] : Message: Unknown fragment

angular - 在 Angular 中使用 apollo 捕获 http 状态代码

graphql - GraphQL 中的输入类型有何意义?

使用 prisma 和 graphql 测试流程

javascript - 如何将对象数组从 js 客户端传递给 graphql 查询

javascript - 网络错误 : Unexpected token < in JSON at position 0 at new ApolloError