simple way to fetch data using graphQl and Apollo

Hi,
Today i am going to show how to fetch data using graphql and apollo client
here first you need two seperate folder one for client and other for server

in server you are going to install graphql, apollo-client etc..
here i am just using graphql playground for displaying the data using queries
for database i am not using any database program just create myself and playing around that

lets see what's there in the server

two important thing need to know about that before

schema :
it's human-readable schema definition language (or SDL) that you use to define your schema and store it as a string.

type-system :
The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has. In the GraphQL schema language

schema

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

//mock data
const data1 = require("../database/mockdata3.json");
// this is typedef we can see this after
const UserType = require("./TypeDefs/UserType");

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    getAllUsers: {                             
      type: new GraphQLList(UserType),
      // you can pass argument 
      args: { Name: { type: GraphQLString } },  
      resolve(parent, args) {
          // write return what you need back
        return data1;
      },
    },
  },
});
// finally we are going to export this 
module.exports = new GraphQLSchema({ query: RootQuery });

typedef - just represent a kind of object you can fetch from your service, and what fields it has

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => ({
//any fields you can define but you must enter the data-type
    Name: { type: GraphQLString  },
    Age: { type: GraphQLInt },
  }),
});

module.exports = UserType;

and finally we need to run this using express or http, here i am using express

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,
    // this is graphql playground field 
    graphiql: true,
  })
);


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

for client you can use any of the framework to fetch that data
and display it

we can see how to get that data from server and display it in client in next post
bye!

21