Arguably GraphQL is one the most popular convention to Fetch or render Data for Front-End or even Store and Update data for Backend. Well, Rest-API is also there as an alternative to GraphQL but there are many Drawbacks Using Rest-API convention.
I won't go deeper into what are the differences between GraphQL and Rest-API since this topic is all about building up a GraphQL server.
We will be making a GraphQL server and will be using Express to Host our server and rest will be manipulated using GraphQL.
First Open up your terminal and make sure you have Nodejs Installed on your Machine. you can cross check that using this command node -v or npm - v, this will show you the working version of Node.
Make a Directory Named gserver using the command mkdir and then cd into the gserver folder.
Next hit the command npm init - -yes this will make a json package for our project.
Next stuff is to add Express to our Project so run npm install express --save,
Make a new file called server.js on the code editor. This is the main file from where our server will be executed so visit the package.json and change the
“main”: “index.js” to “main”: “server.js”.
Open up the server.js Folder and Type up this following code:
First, we need to install 2 dependencies express-graphql and graphql, so on your terminal run: npm i express-graphql graphql
Express is needed to run our express server and express-graphql will make a bridge connection with GraphQL and Express.
we make an instance of the app using const app = express();
app.use( ) acts as a middleware like whatever we pass into the app.use function will serve as a connection of GraphQL and Express.
app.use takes in two parameters one is a route and another is the file which will be used inside the route, for now, we have graphql which is set to true. This is a basic code that you will have to write for nearly starting projects.
app.listen() is used to indicate on which port our app will run.
To run our server run: node server.js
Now our basic server is ready to run but you will see an error on your localhost: 4000/graphql but I want you to run and check out the error as understanding errors make you a better learner.
You see the error which states that the GraphQL middleware doesn't contain a schema file, so now we have to make a schema file.
So what is this Schema file? well in simple words, a schema file is the structure that our graphQL will contain, to be precise it's just like an content of a book or index of a project.
so we make a folder on your project folder and make a schema.js file inside it ( Schema folder -> schema.js
Inside the schema file, we will import our requirements Express as of now and the GraphQL dependencies.
Type the code to your schema.js file:
Don't worry too much that why we did destructure the all the contents to graphql, for now just know that we will be requiring all these stuff later.
Now let's move to do something else building our JSON data server, Json-server is the dependency we will be requiring to make a fake API database to work with.
so stop the current running program in the terminal by pressing ctrl+C on windows and command+C on mac.
add -> npm install json-server --save
Now make a db.json file inside the gserver folder.
Type out this following Code inside db.json:-
We will be having 2 types of fields Users and companies.
Carefully read the JSON file with the data once to understand the fields of users and companies. You see both users and companies have an ID field which is most important as an id of a user or a company can tell your whole details.
I have added a “companyId” field inside user so that we can also evaluate which user works in which company from the user field itself.
We will be further working on building up the relationship with the user and the company.
for now, let's add a second server to host the JSON database, Open up a 2nd terminal and run the command json-server - -watch db.json.
On your web browser visit: http://localhost:3000/users or companies to view their fields.
Now let's build up our schema.js, open up schema.js and make up the User field.
We are making a new constructor function passing a name and a field as an object. Inside the fields, we will input the field and their type as an object.
Next job is to make a RootQuery, a root query is where an query field will be executed first then the RootQuery will decide where to pass the query.
Example:- suppose you pass a query to find a user with id:”23" so the query will pass to the RootQuery and there we have something called resolvers, resolvers will check where to pass the query then it passes the query to the relevant field and then the field gets executed.
Next to fetch the data from the JSON server we can use fetch() or axios.get(), here I will using my favorite axios.get().
So on terminal install axios by typing npm install axios -- save.
next import by typing this one line on schema.js:
const axios = require(‘axios’);
Now type out this code in schema .js under UserType:
We are doing the same for RootQuery, making a constructor passing 2 objects as name and fields.
Inside the fields we have user as we will be making resolver for user, inside we have a type: UserType same as the name of the constructor.
args is basically arguments that we want a query to execute, here we want the graphQl to query the id.
We have the main resolver after that, we pass 2 arguments root and args, in most of the time inside RootQuery we won't be using root by still we have to have that as an arguments.
After that, we are simply fetching the id with axios as we passed the id as an argument.
now at the last, you will have to export the RootQuery as thats our main query. Add this to the last of schema.js file:
To run, we have to do another thing inside the server.js, remember we were getting an error when we tried to run the graphQL server first time and we got an error such as schema missing from middleware its time to import the schema that we just made to server.js
import the schema file inside the server.js and add schema to the middleware, NOTE: schema is case -sensitive inside the middleware, it is always lowercase schema.
Now let's run our GraphQl server, on our browser open the link again: http://localhost:4000/graphql. You will see the GraphQL playground coming up.
This is our GraphQL playground where we can write our Queries. To the right, you can see the Documentation Explorer: it is very helpful when we write complex queries, it shows the total structure of our fields.
Click on RootQueryType and you will see this: user(id: String): User
We are ready to run our first Query:
To the left-hand side is our query and the right-hand side is the data that we fetch from the query. The data we get is simply a JSON object.
If you are getting something like user: null please recheck the code or the written query again.
Wow, that was a lot of a task just to run our first Query and I accept that when you are typing out the query for the first time its like so big but once you type your query out you will find everything repetitive.
Next is your JOB, I want you to code the Company field yourself looking at the Users field. It's mostly the same way that we will do.
Here is the next part: