错误:RootQueryType.resolve字段配置必须是一个对象。

8

我刚接触GraphQl,创建了我的第一个schema后遇到了这个错误

Error: RootQueryType.resolve field config must be an object
    at invariant (/Applications/Node/users/node_modules/graphql/jsutils/invariant.js:19:11)
    at /Applications/Node/users/node_modules/graphql/type/definition.js:360:56
    at Array.forEach (native)
    at defineFieldMap (/Applications/Node/users/node_modules/graphql/type/definition.js:357:14)
    at GraphQLObjectType.getFields (/Applications/Node/users/node_modules/graphql/type/definition.js:311:44)
    at typeMapReducer (/Applications/Node/users/node_modules/graphql/type/schema.js:209:25)
    at Array.reduce (native)
    at new GraphQLSchema (/Applications/Node/users/node_modules/graphql/type/schema.js:98:34)
    at Object.<anonymous> (/Applications/Node/users/schema/schema.js:39:18)
    at Module._compile (module.js:569:30)

这是我的模式。
const graphql = require('graphql');
const _ = require('lodash');
const{
    GraphQLObjectType,
    GraphQLInt, 
    GraphQLString,
    GraphQLSchema
} = graphql;

const users = [
    {id:'23', firstName:'Bill', age:20},
    {id:'47', firstName:'Samantha', age:21}
];

const UserType = new GraphQLObjectType({
    name: 'User',
    fields:{
        id: {type: GraphQLString},
        firstName: {type: GraphQLString},
        age:{type: GraphQLInt}
    }
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields:{
        user: {
            type: UserType,
            args:{
               id: {type: GraphQLString}
            }
        },
        resolve(parentValue, args){
            return _.find(users, {id: args.id});
        }
    }
});

module.exports = new GraphQLSchema({
    query: RootQuery
});

2
看起来你正在跟随 Stephen Girder 的课程。是这样吗? :) - Jeevan Varughese
我现在正在上这门课程。我不知道这门课程已经有五年了,几乎快六年了。 - Richard Jessop
1个回答

19

您的GraphQL模式无效,因为您将解析函数放错位置了,应该放在RootQuery对象中。

尝试这样做:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields:{
        user: {
            type: UserType,
            args:{
               id: {type: GraphQLString}
            },
            resolve(parentValue, args){ // move the resolve function to here
                return _.find(users, {id: args.id});
            }
        },

    }
});

谢谢。那就是问题所在。你救了我数天的调试时间。 - Dike Jude

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接