GraphQL循环引用的问题
Posted time-is-life
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GraphQL循环引用的问题相关的知识,希望对你有一定的参考价值。
下面的代码中, 由于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: { type: GraphQLString, resolve : function (person) { return person.first_name; } }, lastName: { type: GraphQLString, resolve : function (person) { return person.last_name; } }, department: { type: GraphQLString, resolve : function (person) { 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( { name: ‘Person‘, description: ‘...‘, fields: ()=>({ id: { type: GraphQLString, resolve : function (person) { return person.first_name; } }, firstName: { type: GraphQLString, resolve : function (person) { return person.first_name; } }, lastName: { type: GraphQLString, resolve : function (person) { return person.last_name; } }, department: { type: GraphQLString, resolve : function (person) { 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; //} } }) }); |
原理就是把fields放到函数中后,会在另一个线程中执行,所以执行的时候PersonType已经创建完成,所以就不会报错了.
以上是关于GraphQL循环引用的问题的主要内容,如果未能解决你的问题,请参考以下文章