Skip to main content

Understanding GraphQL for beginners ( CRUD Ops with Node.js)

le, we shall try to get a basic idea of how we can use GraphQL queries to fetch the required data, instead of using the traditional REST API approach. We shall be doing so by performing the basic CRUD operations with Node.js at the server-side. This is not a detailed course on GraphQL, it is more of an introductory course to GraphQL, which would be sufficient for you to begin working with GraphQL queries. Alright then, without any further adieu, let’s begin with it. Let us first understand what GraphQL actually is & why do we need to use it.

  • GraphQL is a modern way of building & querying APIs.
  • It was developed by Facebook & released publicly in 2015.
  • It is generally used to load the data from a server to the client-side.
  • Aggregation of data from multiple sources has been made quite easy by GraphQL.
  • It uses a type system to describe the data required.

Now, the bigger question is Why do we need GraphQL? GraphQL lets the user make a single call to fetch the required information rather than constructing several REST requests to fetch the same data. Bigwigs like FacebookTwitterInstagram use GraphQL in their tech stack for querying the data. 

CRUD Application

Now, let’s move on to the intended section of this article. We shall be writing queries to fetchcreateupdate & delete data. Before that, let’s create a basic Node.js server file that looks like this –

Basic setup of server.js file

Here, we are –

  • Initializing our server at PORT 4000.
  • Using package called express-graphql (Used to create a GraphQL HTTP server with any HTTP web framework that supports connect styled middleware, for example, Express.js in our case)
  • Setting up the schema (This is where we shall be writing all our queries).
  • Setting up graphql as true, that lets us use the GraphQL IDE.

Talking about the GraphQl IDE, it is an in-browser tool for writing, validating, and testing the GraphQL queries. To access the GraphQL IDE, you can start the server using “nodemon server.js” and then visit http://localhost:4000/graphql. You will see a window like this –

GraphQL IDE

The left part of the IDE (where welcome message & introductions are written) is where we shall be writing the GraphQL queries. The right side of the IDE (the blank grey space) is where we shall see the responses relevant to the queries. So, before we start writing queries, let’s import some necessary stuff in our schema.js file.

importing object types to be used from package graphql

Here, we are importing the Object types that would be used for the relevant data types in the queries we shall be writing. For example, for integer values, we can use GraphQLInteger & for string values, we can use GraphQLString. Now, we shall be using a public REST API jsonplaceholder, using which we shall write GraphQL queries to perform CRUD operations related to posts. For the sake of simplicity, we shall be using the idtitle & body attributes from the API response. Now that we know our datatypes, we can define the field types to be used for our GraphQL queries, like so –

Creating posts type & setting object types fro fields to be used.

Here, we are using GraphQLString type for all the three attributes, that is, id, title & body. Now, we shall be writing a root query, which would act like a base for all other queries.

Setting up the root query

As you can see that, we’ve written a root query (line number 21), and here we can set the fields. Inside fields, we can write all the queries we want. Let’s begin writing all the queries –

1. GraphQL query to fetch all posts

Writing GraphQL query to fetch all posts

The first query we’re writing down is that of fetching all the posts. Inside the fields, the query has been name posts, the type has been set to PostsType (the one, where we have set up object types for the attributes we will use). Next, we’re using resolve function, in which we are using axios to make call to the desired endpoint, following which, we’re simply just returning the response data. Now, to see its action in working, we can open GraphQL IDE (localhost:4000/graphql), and start using our first GraphQL query to retrieve all the posts.

Testing the query to fetch all posts in GraphQL IDE

Here, we’re firstly using parantheses to start writing a query, then, we’re using the name of query we need to use (remember, we wrote posts as the name of our first query earlier?). After that, we need to define what all attributes we need to fetch from the API response. For now, we are using all the three attributes. You can try the same, and play around with removing any one these. After writing this, we need to hit the play icon that sits right to the GraphQL text at top left corner.

After we hit this, we receive the desired response at the right side of IDE, like so –

Response for fetching all the posts in GraphQL IDE

See this? Well, we’ve just written & executed our first GraphQl query. It wasn’t as hard as you must’ve assumed it to be? Right? Alright then, in the same way, we can write another query to retrieve a particular post using its Id.

GraphQL query to retrieve a post using an ID

To fetch a post using its id, we can write the post query. The only difference between the posts query and post query is that, in order to use the id, we have to first define it in the args (after type), and also, we need to write args as argument inside the resolve function. From args, we can fetch the id (as requested from the client-side or GraphQL IDE in this case) and use it in the endpoint to fetch a particular post. Now, we can turn back to the GraphQL IDE & test this query.

GraphQL query & its response inside IDE

Here, we are using post query and putting in the id that we want. Remember, we have defined GraphQLString type for id? That’s the reason, we are setting the id as a string here. Like we did in the posts query, we can set the values we want like id, title & body and hit (Ctrl + Enter). You should see the response with the post associated to the requested id. Now, before we proceed further to understand the mutations, I’d suggest you to take some time in absorbing the things we’ve done by playing around with 2 queries we’ve written so far.

Mutations

Now, in order to make changes to the server side data, we can use mutations in GraphQL. Mutations are used to modify the server side data. These are very simple to use & are quite similar to the Queries. Let’s start with the mutations part –

Setting up mutations

See? This is quite similar to what we did while writing the queries. Inside the fields, we can write all the queries to mutate the server side data. Alright so, let’s begin –

1. Creating a new post

To add a new post, we can begin with writing a addPost query like so –

GraphQL query to add a new post

Here, we’re setting the PostsType, like we did in the previous queries, In args, we’re using GraphQLNonNull to set title and body as required input fields (id is being auto generated at the server side). Now, we can go to the GraphQL IDE and try creating a new post.

Testing addPost query & response in GraphQL IDE

We’re beginning off with writing mutation first, following which, we are using the addPost query. Here, we need to define a title & body (like we used id while retrieving a particular post) and mention what data we need from the response. After hitting (Ctrl + Enter), you can see that, we’ve successfully added a new post that shows all the required data values we asked for. Now, similarly, we can write queries for updating & deleting a post. For deleting, we are using query name deletePost and for editing, we are using editPost. Rest, everything is exactly similar to queries we have written so far.

2. Deleting a post

GraphQL query to delete a post

3. Updating a post

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...