GraphQL Mutation类型报错,无法实现添加用户功能求解决
问题排查:GraphQL Mutation定义报错"Mutation fields must be an object..."
错误提示:
"Mutation fields must be an object with field names as keys or a function which returns such an object."
尝试通过GraphQL实现添加用户功能但无法运行,以下是相关代码:
Mutation类型定义
const mutation = new GraphQLObjectType({ name: "Mutation", fileds: { addUser: { type: UserType, args: { firstName: { type: new GraphQLNonNull(GraphQLString) }, age: { type: new GraphQLNonNull(GraphQLInt) }, companyId: { type: GraphQLString } }, resolve(parentValue, { firstName, age }) { return axios.post("http://localhost:3000/users", { firstName, age }).then(r => r.data); } } } })
UserType定义
const UserType = new GraphQLObjectType({ name: "User", fields: { id: { type: GraphQLString }, firstName: { type: GraphQLString }, age: { type: GraphQLInt }, company: { type: CompanyType, resolve(parentValue, args) { return axios.get("http://localhost:3000/companies/" + parentValue.companyId).then(res => res.data) } } } })
解决方法
修复拼写错误:
问题根源是Mutation定义里的属性名写错了——fileds应该改为fields(少了一个字母e)。GraphQL要求类型定义必须包含fields属性来声明字段,拼写错误导致框架无法识别合法的字段配置,因此抛出该错误。可选优化:处理companyId参数:
你的addUser的resolve函数目前只用到了firstName和age,但args里定义了companyId,如果需要在创建用户时一并传入该参数,需要修改resolve函数:resolve(parentValue, { firstName, age, companyId }) { return axios.post("http://localhost:3000/users", { firstName, age, companyId }).then(r => r.data); }
内容的提问来源于stack exchange,提问作者FaFa
相关产品推荐
相关产品推荐

