DEV Community

karthikeyan
karthikeyan

Posted on

create a Mock API using graphQl and Apollo

install these packages

    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-graphql": "^0.12.0",
    "graphql": "^15.4.0"
Enter fullscreen mode Exit fullscreen mode
UserType.js

const graphql = require("graphql");
const { GraphQLObjectType, GraphQLInt, GraphQLString } = graphql;

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => ({
   //any fields
      Name: { type: GraphQLString  },
      age: { type: GraphQLString  },
  }),
});

module.exports = UserType;

Enter fullscreen mode Exit fullscreen mode
Schema.js

const graphql = require("graphql");
const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLString,
  GraphQLList,
} = graphql;

//import mock data here
const UserType = require("./UserType");

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    getAllUsers: {
      type: new GraphQLList(UserType),
      args: { Name: { type: GraphQLString } },
      resolve(parent, args) {
       //return mock data
        return data;
      },
    },
  },
});

module.exports = new GraphQLSchema({ query: RootQuery });
Enter fullscreen mode Exit fullscreen mode
index.js 

const express = require("express");
const app = express();
const PORT = 6969;
const { graphqlHTTP } = require("express-graphql");
const schema = require("./Schemas/Schema");
const cors = require("cors");

app.use(cors());
app.use(express.json());
app.use(
  "/data",
  graphqlHTTP({
    schema,
    graphiql: true,
  })
);
Enter fullscreen mode Exit fullscreen mode

Discussion (0)