下面的代码中, 由于friends字段引用了PersonType字段,而friends本身又是PersonType的一部分,在运行的时候会报错:
Expected undefined to be a GraphQL type
var PersonType = new GraphQLObjectType({
name: 'Person',
description: '...',
fields: {
id: {
type: GraphQLString,
resolve : function (person) {
return person.first_name;
}
},
firstName: {
lastName: {
return person.last_name;
department: {
return person.department;
//email: { type: GraphQLString },
//userName: { type: GraphQLString },
//id: { type: GraphQLString },
friends: {
type: GraphQLList(PersonType)
//resolve: function (person) {
// //return person.friends.map(getPersonByUrl);
// return person.friends;
//}
}
});
原因在于GraphQLList初始化的时候会检查PersonType的类型,而此时PersonType的定义尚未完成,所以还是undefined, 所以会报上面的错误.
[解决方案]
搜索到了这篇文章: https://gist.github.com/fbaiodias/77406c29ddf37fe46c3c
Fix
Using a function to return the fields on author.js does the trick:
On author.js
@@ -13 +13 @@
- fields: {
+ fields: () => ({
把代码改成下面的就可以了.
var PersonType = new GraphQLObjectType( {
fields: ()=>({
id: {
type: GraphQLString,
resolve : function (person) {
return person.first_name;
},
firstName: {
lastName: {
return person.last_name;
department: {
return person.department;
//email: { type: GraphQLString },
//userName: { type: GraphQLString },
//id: { type: GraphQLString },
friends: {
type: GraphQLList(PersonType)
}
})
原理就是把fields放到函数中后,会在另一个线程中执行,所以执行的时候PersonType已经创建完成,所以就不会报错了.