![](/img/trans.png)
[英]TypeError: Cannot read property 'createProduct' of undefined ? (from graphql mutation.js file)
[英]Custom type in GraphQL mutation
我正在使用GraphQL js 。我想在其中实现一对多关联。我有两种类型的用户和Office 。一个用户有很多办公室。
用户类型:
var graphql = require('graphql');
const userType = new graphql.GraphQLObjectType({
name: 'user',
fields :()=>{
var officeType=require('./officeSchema');
return {
_id: {
type: graphql.GraphQLID
},
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
},
office:{
type:officeType
}
};
}
});
module.exports=userType;
officeSchema:
const officeType = new graphql.GraphQLObjectType({
name: 'office',
fields:()=> {
var userType = require('./userSchema');
return {
_id: {
type: graphql.GraphQLID
},
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
},
users: {
type: new graphql.GraphQLList(userType),
resolve: (obj,{_id}) => {
fetch('http://0.0.0.0:8082/office/user/'+obj._id, {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res) {return res});
}
}
};
}
});
现在,变异代码如下:
const Adduser = {
type: userType,
args: {
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
}
},
resolve: (obj, {
input
}) => {
}
};
const Addoffice = {
type: OfficeType,
args: {
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
},
users: {
type: new graphql.GraphQLList(userInputType)
}
},
resolve: (obj, {
input
}) => {
}
};
const Rootmutation = new graphql.GraphQLObjectType({
name: 'Rootmutation',
fields: {
Adduser: Adduser,
Addoffice: Addoffice
}
});
此代码将错误抛出为
Rootmutation.Addoffice(users :)参数类型必须为Input Type,但必须为:[user]。
我想在数据库中以及关联表的字段中添加实际字段,但无法找出问题所在。
更新:
1-添加GraphQLInputObjectType:
const officeInputType = new graphql.GraphQLInputObjectType({
name: 'officeinput',
fields: () => {
return {
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
}
}
}
});
const userInputType = new graphql.GraphQLInputObjectType({
name: 'userinput',
fields: () => {
return {
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
}
}
}
});
2-添加了userinputtype而不是AddOffice中的usertype。
现在的错误是
Rootmutation.Addoffice(user:) argument type must be Input Type but got: userinput.
问题是,您所提供userType
作为参数类型为之一Addoffice
突变。 userType
不能为参数类型。 相反,您必须使用输入类型。
有两种对象类型:输出和输入类型。 您的userType
和officeType
是输出类型。 您需要使用GraphQLInputObjectType
[ docs ]创建输入类型。 它可能会有非常相似的领域。 您可以在参数字段中将其用作类型。
const userInputType = new graphql.GraphQLInputObjectType({
name: 'UserInput',
fields () => {
return {
_id: {
type: graphql.GraphQLID
},
// ...
};
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.