Javascript &引用;类型RootQueryType必须定义一个或多个字段。";}
试图让GraphQL与JavaScript一起工作。不知道我的错在哪里 我的代码Javascript &引用;类型RootQueryType必须定义一个或多个字段。";},javascript,express,graphql,graphql-js,express-graphql,Javascript,Express,Graphql,Graphql Js,Express Graphql,试图让GraphQL与JavaScript一起工作。不知道我的错在哪里 我的代码 const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } = graphql; const users = [ { id: "23", firstName: "Bill", age: 2
const graphql = require('graphql');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql;
const users = [
{ id: "23", firstName: "Bill", age: 20},
{ id: "47", firstName: "Sam", 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
});
我越来越
{“错误”:[
{
“消息”:“类型RootQueryType必须定义一个或多个字段。”
}
]}
为什么它不起作用?我相信你的错误就在于你的提问。使用RootQueryType的
字段
对象创建查询端点。您案例中的字段
对象只包含一个查询:用户
。但是,您尝试对用户
进行查询,这是不同的
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
// The items listed here are going to be your root query endpoints.
// Which in this case is only `user`.
user: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(users, { id: args.id });
}
}
}
});
因此,您需要使用user
进行查询
此外,您需要确保您的查询是正确的。您试图实现的基本查询语法如下所示:
{
user(id: "23") {
id
firstName
age
}
}
让我知道这是否适合你
关于查询的一些文档:
您忘了使用箭头功能
const UserType = new GraphQLObjectType({
name: 'User',
fields:()=>( {
id: {type: GraphQLString},
firstName: {type: GraphQLString},
age:{type: GraphQLInt}
});