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