Monday, May 27, 2019

GraphQL with NodeJS

In this post, we are going to create a GraphQL API using NodeJS.
First, we will install the required node modules for the GraphQL API.
Then, we will create Student, Course and CourseRegistration models like below.
Next, we will focus on creating student functionality. In order to do that, we must define GraphQL schema for that. Create index.js file inside graphql/schema directory.
Then we will add a mapping resolver file to create student functionality. We call it auth.js and put it inside graphql/resolvers directory. When we create the student, we must encrypt the password. Therefore, we will use bcrypt node module for that.
As we are going to have many resolvers, we can define a central resolver file like below.
Next, we need to start the NodeJS backend server like below.
As we have enabled, graphiql: true we can make open graphiql console and create a student like below.
In the above implementation, we created a GraphQL mutation functionality. Now we are going to create a query functionality using GraphQL.
First, we add a query for Courses. Then we implement functionality to fetch courses.
We can use graphiql interface to query courses.
Now, we have created basic functionality of a GraphQL API. As developers, we must know how to trigger GraphQL API endpoint using HTTP. I am using Advanced Rest Client tool like below.
After that, you will see the return result like below.
You can download the source code for this application from GitHub.

1 comment: