gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:31:27 29 4
gpt4 key购买 nike

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com