给定以下GraphQl类型定义:
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)
}
`
根据规格:
枚举值表示为未引用的名称(ex。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
}
})
}
使用上述edit_profile的突变:
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,就像我使用性别一样 gql突变中的 $gender: Gender!
.您不必担心将数据作为枚举发送,只需将其发送为字符串,否则您将必须面对JSON错误,GraphQl将照顾您发送的值作为字符串(例如'Male''或"女性")只是不要忘记提到性别是GQL突变中的性别类型(这是枚举)。