[英]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.