Types GraphQL-将枚举值作为参数直接传递给变异?
给定以下GraphQL类型定义:Types GraphQL-将枚举值作为参数直接传递给变异?,types,enums,graphql,Types,Enums,Graphql,给定以下GraphQL类型定义: const typeDefs = ` enum Action { update delete } type Mutation { doSomething(action: Action) } `; 此查询可用于: const query = ` mutation($action: Action) { doSomething(action: $action) } ` const variables
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不支持将枚举值直接作为参数传递吗?GraphQL支持将枚举值直接作为参数传递;但是,您需要省略值周围的引号才能使其正常工作:
const query = `
mutation {
doSomething(action: update)
}
`
根据报告:
枚举值表示为不带引号的名称(例如MOBILE_WEB)
因此,与字符串值不同,枚举值不应放在引号内。将它们用于变量时,我们这样做的唯一原因是遵循正确的JSON格式。后端中定义的枚举是:
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
}
})
}
上面使用的突变编辑_配置文件:
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变异中。您不必担心将数据作为enum发送,只需将其作为字符串发送,否则您将不得不面对JSON错误,Graphql将处理您作为字符串发送的值(如“男性”或“女性”),只是别忘了在gql变异中,性别是性别的类型(即enum),正如我前面所做的那样。是我吗,或者使用枚举会使通过变量对象传入参数变得困难吗?