GraphQL query for companyID

Hi, in this post we are going to query the company details, so we are going to create the query, resolver and render the data into the client.

If you want to read the last post please click here GraphQL handling GraphQL error responses

If we open our browser in /companies/id we are going to see an error because we don’t have, So, first let’s add the company id to our company schema:

type Query {
  company(id: ID!): Company
  job(id: ID!): Job
  jobs: [Job]
}

type Company {
  id: ID!
  name: String
  description: String
}

type Job {
  id: ID!
  title: String
  description: String
  company: Company
}

The second step is create our resolver for this schema, so let’s go to the resolvers (in server side):

// Data
const db = require("./db");

const Query = {
  // Job return specific job given an Id
  job: (root, { id }) => db.jobs.get(args.id),
  // Company return specific company given an Id
  company: (root, { id }) => db.companies.get(id),
  // Jobs resolver that return an array of jobs
  jobs: () => db.jobs.list(),
};

const Job = {
  company: (job) => db.companies.get(job.companyId),
};

module.exports = { Query, Job };

Nice, next step is create the function that will fetch the data of our company passing and id, let’s add that function into our request.js (client side):

// GraphQL endpoint
const endpointURL = "http://localhost:9000/graphql";

// Generic function
async function graphRequest(query, variables = {}) {
  // variables is optional
  const response = await fetch(endpointURL, {
    method: "POST",
    headers: { "content-type": "application/json" }, // The type is json
    body: JSON.stringify({
      // Convert a JavaScript object into a string
      query,
      variables,
    }),
  });

  const responseBody = await response.json(); // Converting the response to json format

  // {"errors":[{"message":
  if (responseBody.errors) {
    const message = responseBody.errors
      .map((error) => error.message)
      .join("\n");
    throw new Error(message);
  }

  return responseBody.data;
}

//  Function that fetch data for specific Job details
export async function loadJob(id) {
  const query = `query JobQuery ($id: ID!) { 
    job(id: $id) {
      id
      title
      description
      company {
        id
        name
      }
    }
  }`;
  const { job } = await graphRequest(query, { id });

  return job;
}

// Function that will call the GraphQL endpoint passing specific query
// to get the data that the query specifies
export async function loadJobs() {
  const query = `{
    jobs {
      id 
      title
      company {
        id
        name
      }
    }
  }
`;
  const { jobs } = await graphRequest(query);

  return jobs;
}

//  Function that fetch data for specific Company details
export async function loadCompany(id) {
  const query = `query CompanyQuery ($id: ID!) { 
    company(id: $id) {
      id
      name
      description
    }
  }
  `;
  const { company } = await graphRequest(query, { id });

  return company;
}

Ok and finally we can execute the loadCompany into our component and get the data for specific company using the company id:

import React, { Component } from "react";
import { companies } from "./fake-data";

// Importing loadCompany to fetch company by id
import { loadCompany } from "./request";

export class CompanyDetail extends Component {
  constructor(props) {
    super(props);
    const { companyId } = this.props.match.params;

    this.state = {
      company: companies.find((company) => company.id === companyId),
    };
  }

  // When component did mount
  async componentDidMount() {
    const { companyId } = this.props.match.params;
    const company = await loadCompany(companyId);
    this.setState({ company });
  }

  render() {
    const { company } = this.state;

    // If we don't have the company data then return null
    if (!company) {
      return null;
    }

    return (
      <div>
        <h1 className="title">{company.name}</h1>
        <div className="box">{company.description}</div>
      </div>
    );
  }
}

By Cristina Rojas.