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

lid*_*ang 7 apollo graphql apollo-client vue-apollo

枚举定义在 OrderTypesEnum.gql

enum OrderTypes {
  full_buy
  pink_buy
}
Run Code Online (Sandbox Code Playgroud)

导入 OrderTypesEnum.gql 文件

import OrderTypes from '@/graphql/OrderTypesEnum.gql'`
Run Code Online (Sandbox Code Playgroud)

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

我使用OrderTypes.full_buy 得到一些错误:

   self.$apollo.mutate({
        mutation: createOrder,
        variables: {
          subjectId: self.subject.id,
          types: OrderTypes.full_buy
        }
      })
Run Code Online (Sandbox Code Playgroud)
Mutation createOrderMutation error: Invariant Violation: Schema type definitions not allowed in queries. Found: "EnumTypeDefinition"
Run Code Online (Sandbox Code Playgroud)

OrderTypes 类型枚举的检查

在此处输入图片说明

Vil*_*ami 8

先决条件:

<SomeEnumType> 在 GraphQL schema 中定义(服务器端,无需客户端配置)

假设我们有:

enum SomeEnumType {
    OPTION1,
    OPTION2,
    OPTION3
}
Run Code Online (Sandbox Code Playgroud)

Apollo 客户端应以适当的方式配置并与 GraphQL API 连接。

然后在客户端:

enum SomeEnumType {
    OPTION1,
    OPTION2,
    OPTION3
}
Run Code Online (Sandbox Code Playgroud)

只有通过这样做,我们才能将枚举作为查询或突变中的变量传递。例如,使用useMutationhook 我们现在可以进行如下变异:

export const OUR_MUTATION = gql`
    mutation ourMutation($foo: SomeEnumType){
        ourMutation(foo: $foo){
            bar
        }
    }    
`
Run Code Online (Sandbox Code Playgroud)

由于 tag 中的类型定义gql等于 Schema 中的定义,因此 GraphQL 将变量识别为枚举类型,尽管将其作为字符串给出。

如果我们想使用打字稿枚举将枚举传递给变量,我们可以这样做:

const [ourMutation] = useMutation(OUR_MUTATION, {
        variables: {
            foo: "OPTION2"
        },
Run Code Online (Sandbox Code Playgroud)

更新:字符串枚举和类型生成

就我个人而言,我建议如果可能的话使用字符串枚举。字符串枚举的使用更加简单。

enum SomeEnumType {
    OPTION1 = 0,
    OPTION2 = 1,
    OPTION3 = 2
}

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

Run Code Online (Sandbox Code Playgroud)

对于下一级编码,枚举类型和所有其他类型定义可以使用graphql-codegen自动生成到前端。我真的建议使用这种方法,因为后端架构更新和添加可以直接反映在您的前端代码中,从而揭示错误并帮助您更快、更可靠地编写代码。


Edm*_*ues 3

正如错误消息所示,Schema type definitions not allowed in queries.您无法在操作文档(ExecutableDefinition)中添加枚举定义。您只能有操作(查询、突变或订阅)或片段定义。也就是说,这是无效的:

enum OrderTypes {
  FULL_BUY
  PINK_BUY
}

mutation createOrderMutation {
  ...
}
Run Code Online (Sandbox Code Playgroud)

如果要在客户端定义本地枚举,可以在ApolloClient初始化期间使用 typeDefs 属性:

enum OrderTypes {
  FULL_BUY
  PINK_BUY
}

mutation createOrderMutation {
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后您将能够在客户端自省(即 Apollo 扩展)上看到 OrderTypes 枚举。

请注意客户端亮点:如果您尝试使用此枚举发送非客户端字段的请求(即没有 @client 指令)并且它通过您的服务器进行,​​您将收到一个架构错误,指出枚举类型不存在,除非您在后端定义它。