Thursday, May 27, 2021

Fetch the data from the fake api server created

 Previous post, we created a fake api server.


In this post, we will utilize that.


to test this data asynchronously:

---

npm i --save axios


axios adds extra padding of {data: } surrounding the main data.

And graphql doesn't know that.

so, we need to trim it as seen in the code below.



schema\schema.js:
const graphql = require("graphql");
const axios = require("axios");
const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } = graphql;

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 axios
          .get(`http://localhost:3000/users/${args.id}`)
          .then((resp) => resp.data);
      },
    },
  },
});

module.exports = new GraphQLSchema({
  query: RootQuery,
});

server.js

const express = require("express");

const expressGraphQL = require("express-graphql").graphqlHTTP;
const schema = require("./schema/schema");

const app = express();

app.use(
  "/graphql",
  expressGraphQL({
    schema//es6 equavalant to schema: schema
    graphiql: true,
  })
);

app.listen(4000, () => {
  console.log("Listening");
});

 
to start the api server: npm run json:server 

to run the main app: node server.js

to run the request: 
sample query in the graphql:

{
    user(id"40"){
      id,
      firstName,
      age
    }
   }

No comments:

Post a Comment