I am learning GraphQL and I faced an error due while trying to start a server.
const graphql = require('graphql');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql;
const Users = [
{ id: '23', firstName: 'Bill', age: 20 },
{ id: '41', firstName: 'Jane', age: 18 }
];
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: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
and the server.js code is here:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema/schema');
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.listen(4000, () => {
console.log("Server running at port 4000.");
});
The error seems to be coming from the "module.exports" section as when I comment it out the server starts without a problem.
CodePudding user response:
There is syntax confusion. In RootQuery the type part under user completely covers the whole field structure, error is here.
Just remove top level type: {}
.
Try this out:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
});
CodePudding user response:
Thank you, the solution helped me. It now makes a lot of sense.