DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev

GraphQL with Apollo Server and Express - GraphQL Series - Part 1

In this article series, we will see how to implement GraphQL with Apollo Server and Express - GraphQL Series - Part 1

Before going into the topic of graphql, let me ask you few questions about how web works?

  • How a web page in the browser(client) and server communicate?
  • what is stateless and stateful communication between client and server?
  • what is HTTP/1.1? why does it exist?

you can ask me, why do i need to know these things first. that's a good question to ask every time before you learn something new.

If you can answer these questions, you can able to understand why we need something like GraphQL.

Let me try to make it simpler by giving you some scenarios. First of all, we all know that we use REST API for web page(client) and server(server) communication.

REST API is nothing but an API endpoint, which gives the data when we hit a particular route.

Now, you can ask me, it works fine as we expect, then what's the problem with it. Let's say that you need to get only the email address from the result of the particular API which contains the hundred's and thousand's of data.

It is very difficult to loop the data in the web browser and display only the email address. it will affect the performance of an application.

That's where GraphQL comes in

What is GraphQL ?

GraphQL is an alternative to REST API's. Unlike REST API's, GraphQL fetches what is only needed for the client side of the application.

Instead of returning all the data from the server, GraphQL returns only what client seeks for.

Let's say that you need email and password from the users table. GraphQL query can only fetch those details from the server.

GraphQL provides lot of flexibility in data handling and solves the problem of loading lots of unnecessary data in the client side.

How GraphQL works ?

Above all, GraphQL has only single endpoint which sends the request as query and gets the response back from the server.

  • client hits the /graphql endpoint with a query.
  • graphql sends the request details in the body of the request to the server.
  • the server responds to the request with a data.

GraphQL Building Blocks

Mainly, there are two ways to get the data from server to client.

  • Query - it is something similar to GET request in REST API's. with Query, we can fetch the data from the server.
  • Mutation - mutation in GraphQL is used to update the data in the server. it is similar to POST request in the server.
  • Subscription - it is used to handle the real-time communication between client and server using web sockets.
  • Type Definitions - Type Definitions is nothing but defining the request and response format for a particular query

GraphQL Query Structure

  • Operation Type - we need to define what kind of operation that we need to perform. For Example, To fetch the Data, we need to define it as a query
  • Operation Endpoint - it defines the operation that you are going to perform whether it is a Query or Mutation
  • Query Arguments - it is something like a query parameter.
  • Requested Field - it defines the data that we need to fetch from the server

Implementing GraphQL

I assume that you are familiar with Node.js and Express framework.

create a folder and install the following dependencies

$ mkdir graphql-demo
$ cd graphql-demo
$ npm init --yes
$ npm install express body-parser graphql apollo-server-express

Mainly, graphql library is the core library package to run the graphql. apollo-server-express is used to connect the graphql and express server

create a file called index.js and add the following code.

import express from 'express'
import bodyParser  from 'body-parser';
import { ApolloServer } from 'apollo-server-express';
import typeDefs from './typedef';
import resolvers from './resolver';
const app = express();

app.use(bodyParser.json());

const server = new ApolloServer({
    introspection : true,
    typeDefs,
    resolvers,
    formatError: error => {
        return error
    },
    context : ({req,res}) => {
        return {
            req,res
        }
    }
})

server.applyMiddleware({app,path : '/graphql'})

app.listen(3030,() => {
    console.log("app is listening to port 3030");
})

there are two ways to configure the graphql server. one is Apollo server and another is express graphql.

we are using apollo server to configure graphql in this tutorial.

There are two things to notice in the index.js. they are typeDefs and resolvers.

  • typeDefs - Type Definitions is defining the format of request and response
  • Resolvers - Resolver is a function which handles the request and returns the data from the server.

create a file called typeDefs.js and add the following code.

import {gql} from 'apollo-server-express';

const typeDefs = gql`

type Author {
    id : Int!
    firstName : String
    lastName : String
    posts : [Post]
}

type Post {
    id : Int!
    title : String
    authorId : ID!
    votes :Int
}

input PostData {
    id : Int!
    title : String
    authorId : ID!
    votes :Int
}

type Response {
    success: Boolean
}

type Query {
    
    posts : [Post]
    author(id : Int!): Author
}

type Mutation {
    createPost(post : PostData) : Response
}
`
export default typeDefs;

you need to define Query and Mutation in the type definition. As I said before, Query and Mutation are similar to GET and POST.

  • Posts Query gets all the post data.
  • Author Query fetch all the Data for the Particular author id
  • Create Post Mutation gets the Post data from the request and updates it in the database

create a file called in resolver.js and add the following code.

import { find, filter } from 'lodash';

const authors = [
    { id: 1, firstName: 'Tom', lastName: 'Coleman' },
    { id: 2, firstName: 'Sashko', lastName: 'Stubailo' },
    { id: 3, firstName: 'Mikhail', lastName: 'Novikov' },
  ];
  
  const posts = [
    { id: 1, authorId: 1, title: 'Introduction to GraphQL', votes: 2 },
    { id: 2, authorId: 2, title: 'Welcome to Meteor', votes: 3 },
    { id: 3, authorId: 2, title: 'Advanced GraphQL', votes: 1 },
    { id: 4, authorId: 3, title: 'Launchpad is Cool', votes: 7 },
  ];
  

export default {

    Query : {
        posts : () => posts,
        author : (_,{ id }) => find(authors,{ id })
    },

    Mutation : {
        createPost: (_,newPost) => {
            // console.log("new post",newPost.post.id);    
            posts.push(newPost.post);
            // console.log("posts",posts);
            let result = {
                success : true
            }
           return result;
        }
    }
}

Instead of Connecting with database, we use Mock data here.

Resolver function gets the data from server and returns it as response. you need to write all the business logic here in resolvers

Complete source code : https://codesandbox.io/s/graphql-demo-hic8p

To sum up, run the command npm run start and visit the url http://localhost:3030/graphql in the browser. you can see something like this.

That's the minimal code to run a simple graphql server.

In the upcoming Articles, GraphQL with Apollo Server and Express - GraphQL Series. we will see how to build a complete web Application with React, Express, and GraphQL.

Until then, Happy coding :-)

Top comments (0)