天天看點

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: {

                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已經建立完成,是以就不會報錯了.