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

时间:2017-07-26 14:02:38

标签: node.js graphql graphql-js

我是GraphQl的新手,刚刚创建了我的第一个模式来查看此错误

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
});

1 个答案:

答案 0 :(得分:9)

您的GraphQL架构无效,因为您错误地放置了RootQuery对象中的resolve函数。

试试这个:

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});
            }
        },

    }
});