Thursday, May 27, 2021

relating company to user in the fake json data

 added compaies data to data.json

{
  "users": [
    { "id""23""firstName""Bill""age"20"companyId""1" },
    { "id""40""firstName""Alex""age"40"companyId""2" },
    { "id""41""firstName""Nick""age"40"companyId""2" }
  ],
  "companies": [
    { "id"1"name""Apple""description""iphone" },
    { "id"2"name""Google""description""search" }
  ]
}

Normal queries:

graphql UI": http://localhost:4000/graphql?query


to fetch user with id: 40 in graphql:

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


to fetch all companies:

http://localhost:3000/users


to fetch all companies:

http://localhost:3000/companies


to fetch first company:

http://localhost:3000/companies/1


to fetch all users from first company:

http://localhost:3000/companies/1/users


Now, to get company data from user id, we need to change schema to add company data to graphql.

//schema/schema.js
const graphql = require("graphql");
const axios = require("axios");
const { GraphQLObjectTypeGraphQLStringGraphQLIntGraphQLSchema } = graphql;

const CompanyType = new GraphQLObjectType({
  name: "Company",
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    description: { type: GraphQLString },
  },
});

const UserType = new GraphQLObjectType({
  name: "User",
  fields: {
    id: { type: GraphQLString },
    firstName: { type: GraphQLString },
    age: { type: GraphQLInt },
    company: {
      type: CompanyType,
      resolve(parentValueargs) {
        //used when field names with database and here are different
        console.log(parentValueargs);
        return axios
          .get(`http://localhost:3000/companies/${parentValue.companyId}`)
          .then((res=> res.data);
      },
    },
  },
});

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    user: {
      type: UserType,
      args: { id: { type: GraphQLString } },
      resolve(parentValueargs) {
        return axios
          .get(`http://localhost:3000/users/${args.id}`)
          .then((resp=> resp.data);
      },
    },
  },
});

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

Next, graphql query:

{
  user(id"23"){
    firstName
    company{
     id
     name
     description
   }
  }
 }

No comments:

Post a Comment