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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...