Error: RootQueryType fields must be an object with field names as keys or a function which returns such an object

61 Views Asked by At

userData is just an array of object with some dummy data something like this

  {
    id: 1,
    first_name: "Deny",
    last_name: "Scrange",
    email: "[email protected]",
    Password: "268403811-2",
  },

So here this is just a program to implement graphql inside expressjs but due to outdated resources i am not able to track the data so I think we need only two things for Graphql one is Type Definitions and second is resolver so for that i created the TypeDefinition called "UserType" then i went and created RootQuery for query field and Mutation for the Mutation and put it inside the Standard form of GraphQlSchema

const express = require("express");
const app = express();
const PORT = 6969;
const userData = require("./FakeData");
const graphql = require("graphql");
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLString,
  GraphQLList,
} = graphql;

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => ({
    id: { type: GraphQLInt },
    firstName: { type: GraphQLString },
    lastName: { type: GraphQLString },
    email: { type: GraphQLString },
    password: { type: GraphQLString },
  }),
});

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  feilds: {
    getAllUsers: {
      type: new GraphQLList(UserType),
      args: { id: { type: GraphQLInt } },
      resolve(parent, args) {
        return userData;
      },
    },
  },
});
const Mutation = new GraphQLObjectType({
  name: "Mutation",
  fields: {
    createUser: {
      type: UserType,
      args: {
        fistName: { type: GraphQLString },
        lastName: { type: GraphQLString },
        email: { type: GraphQLString },
        password: { type: GraphQLString },
      },
      resolve(parent, args) {
        userData.push({
          id: userData.length + 1,
          firstName: args.firstName,
          lastName: args.lastName,
          email: args.email,
          password: args.password,
        });
        return args;
      },
    },
  },
});

const schema = new GraphQLSchema({
  query: RootQuery,
  mutation: Mutation,
});

app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    graphiql: true,
  })
);

app.listen(PORT, () => {
  console.log("Server is running ");
});
0

There are 0 best solutions below