Home » Enterprise Java » sql » Query in graphql

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Query in graphql

Hello readers. In this tutorial, we will understand and implement the query in graphql.

1. Introduction

GraphQL is an API syntax that defines how to fetch data from one or more databases. It was developed by Facebook to optimize the RESTful api calls.

  • It is a data query and manipulation language for api’s. It is faster, simple, and easier to implement
  • It follows the client-driven architecture and gives a declarative way to fetch and update the data
  • It has a graphical structure where objects are represented by nodes and edges represent the relationship between the nodes
  • Provides high consistency across all platforms
  • It doesn’t have any automatic caching system

1.1 Application components in GraphQL

In graphql, there are two types of application components.

  • Server-side components
  • Client-side components

1.1.1 Service-side components

The server-side component allows parsing the queries coming from the graphql client applications and consists of 3 components i.e. query, resolver, and schema. Apollo is the most popular graphql server.

ComponentDescription
QueryA query is a client request made by the graphql client for the graphql server. It is used to fetch values and can support arguments and points to arrays. field and arguments are two important parts of a query
ResolverHelps to provide directions for converting graphql operation into data. Users define the resolver functions to resolve the query to the data. They help to separate the db and api schema thus making it easy to modify the content obtained from the db
SchemaIt is the center of any graphql server implementation. The core block in a schema is known as a type
MutationIt allows to modify the server data and return an object based on the operation performed

1.1.2 Client-side components

The client-side components represent the client which is a code or a javascript library that makes the post request to the graphql server. It is of two types i.e.

  • GraphiQL – Browser-based interface used for editing and testing graphql queries and mutations
  • Apollo client – State management library for javascript that enables local and remote data management with graphql. Supports pagination, prefetching data, and connecting the data to the view layer

1.2 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

2. Query in graphql

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE. Let a take a quick peek at the project structure.

Fig. 2: Project structure

2.1 Setting up project dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –

package.json

{
  "name": "graphql-query",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "apollo-server-express": "^3.8.2",
    "express": "^4.18.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

Once the file is replaced trigger the below npm command in the terminal window to download the different packages required for this tutorial.

Downloading dependencies

npm install

2.2 Setting up mock data

Create a file responsible to mock the database. The below file in the mock directory is responsible to hold the employees’ data. The primary focus of this tutorial is to understand the query and hence we skipped the real database part.

dummy.js

let employees = [
  {
    id: 1,
    name: "George Fall",
    gender: "Male",
    email: "George_Fall7390@bretoux.com"
  },
  {
    id: 2,
    name: "Denis Harper",
    gender: "Male",
    email: "Denis_Harper2856@gembat.biz"
  },
  {
    id: 3,
    name: "Rowan Mackenzie",
    gender: "Female",
    email: "Rowan_Mackenzie3715@ubusive.com"
  },
  {
    id: 4,
    name: "Clint Wright",
    gender: "Male",
    email: "Clint_Wright9278@twace.org"
  },
  {
    id: 5,
    name: "Daria Bryant",
    gender: "Female",
    email: "Daria_Bryant1045@gembat.biz"
  }
];

module.exports = { employees };

2.3 Setting up resolvers

Create a file in the schema directory responsible to interact with the database and address the incoming query and mutation from the client. But here I will focus primarily on the query.

resolvers.js

const { employees } = require("../mock/dummy");

const resolvers = {
  Query: {
    findAll: (parent, args) => {
      console.log("fetching all");
      return employees;
    },

    findByGender: (parent, args) => {
      let key = args.gender;
      console.log("fetching employees with gender = %s", key);
      return employees.filter((item) => item.gender === key);
    },

    find: (parent, args) => {
      let key = args.id;
      console.log("fetch employee with id = %s", key);
      return employees.find((item) => item.id === key);
    }
  }
};

module.exports = { resolvers };

2.4 Setting up type definitions

Create a file in the schema directory responsible to represent the type definition required for the tutorial. The file lists the different query methods such as findAll(), findByGender(…), and find(…).

typedefs.js

const { gql } = require("apollo-server-express");

const typeDefs = gql`
  type Employee {
    id: Int!
    name: String!
    gender: String!
    email: String!
  }

  #Query
  type Query {
    findAll: [Employee!]!

    findByGender(gender: String!): [Employee!]!

    find(id: Int!): Employee
  }
`;

module.exports = { typeDefs };

2.5 Creating the implementation file

Create a file in the root directory that acts as an entry point for the application. The graphql server will be exposed on a port number – 3005 and you can use the apollo server gui to play around with the application.

index.js

const { ApolloServer } = require("apollo-server-express");
const { typeDefs } = require("./schema/typedefs");
const { resolvers } = require("./schema/resolvers");

const server = new ApolloServer({ typeDefs, resolvers });

const express = require("express");
const app = express();

// browser url - http://localhost:3005/graphql

const app_port = 3005;
server.start().then(() => {
  server.applyMiddleware({ app });
  app.listen({ port: app_port }, () => {
    console.log(`Service endpoint :: http://localhost:${app_port}/graphql`);
  });
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal. The application will be started successfully on the port number – 3005.

Run command

$ npm run start

Once the application is started successfully open the browser and hit the below endpoint to view the query explorer. If you will be a first-time user welcome page will be shown otherwise the query explorer.

Application endpoint

http://localhost:3005/graphql
Fig. 3: Application demo

You can download the sample query used in this tutorial from the Downloads section. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we saw a brief introduction to graphql and practical implementation of query in graphql. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial to understand queries in graphql.

Download
You can download the full source code of this example here: Query in graphql

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments