A Simple Demo About GraphQL

Diana
4 min readAug 30, 2020
Photo by AbsolutVision on Unsplash

Today, we are going to talk about the popular GraphQL server -Apollo Server and a few HowTos.

Before we start, let’s have a brief look at some core concepts:

1- Apollo Server is open-source GraphQL server. Everything about it is here.

2- GraphQL is a query language. Here to check out all the details.

3- Schema: is a description of the data clients can request from a GraphQL API. It also defines the queries and mutation functions that the client can use to read and write data from the GraphQL server.

4- Resolver: function for fetching the data for its corresponding field.

5- Mutation: There generally are three kinds of mutations: creating new data, updating existing data and deleting existing data.

Step 1: Create a Node.js Project

In terminal , run the following commands will initialize a new Node.js

npm init --yes // create a Node.js project with a package.json file
npm install apollo-server graphql // install dependencies
touch index.js //

Step 2: Define a schema

The syntax for writing schemas is called the Schema Definition Language, or short SDL. The exclamation point following the type means that this field can not be empty.

Here is a sample schema, in which two types are defined for the demo project.

Step 3: Create a query type

type Query {
books: [Book]

}

add the following code to the index.js in the demo project, to listen to the server.

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

// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});

To create some dummy data in index.js for the demo project, add the following code to index.js as well.

const { ApolloServer, gql } = require('apollo-server');
// fake data
const books = [
{
title: 'Harry Potter and the Philosopher Stone',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];

Step4: Create Resolver

const resolvers = {
Query: {
books: () => {
return books;
},
},
};

Step 5: Start the Server

Run the following command in Terminal and the server starts working now:

Step 6: Party starts Here :) Let’s fetch some data

In GraphQL, make a request like this:

Noticed that once the Play button is clicked, the right hand pin is displaying a list of data in Json format.Viola.

And the beauty of using GraphQL, authorcan be removed from the payload if title is the only field required.

What happened under the hood is, the resolvers will run for every field defined in the query. The execution starts at the query type and goes breadth-first. The resolver for Query.book run first. Then, we take the result of that resolver and pass it into its child.

So the execution works like this:

 Query.book() -> book
Book.title(post, null, context) -> title
Book.author(post, null, context) -> author

At the end, the execution algorithm puts everything together into the correct shape for the result and returns that.

Step 7: To make a change

Suppose that we want to create a new book.

First, we need to create a mutation type like this:

# Mutation
type Mutation {
addBook(title: String, author: String): Book
}

Second, we create a mutation resolver:

const resolvers = {
Query: {
books: () => {
return books;
},
},

Mutation: {
addBook: (root, args) => {
//const newId = require('crypto').randomBytes(5).toString('hex');
const newBook = { title: args.title, author: args.author };
books.push(newBook);
return newBook;
},
},
};

Now, let’s try out and see if we can add a new book by sending a GraphQL request:

And then, we make a request to fetch all the books that we have for now.

Cool.

Remember that this demo server does not have persistence. Once the server is terminated or restarted, the new added books will be disappeared.

That’s all for this simple Apollo Server project demo.

Completed !!

Thank you for checking this article up. And don’t forget to give it some claps! 👏🏼👏🏼👏🏼 if you found it helpful.💡

--

--