Graphql is an alternative approach for the REST API invented by Facebook. It is used for fetch data from a server and put data back to a server , just like the regular API does.
The Graphql shines where you want to fetch few data (required), where REST API fetch a bunch of data, it may cause fetching too much data. API have multiple end points where graphql have one. One of the problem with graphql, it is not simple to create a graphql server, even though once it has been done ,using them is quiet simple.
Play with full code + Graphql Playground in Sandbox
Apollo and Express
With Apollo server we can build and run a graphql server, for creating route for our graphql end point can utilize the node developers favorite express module
Dependencies and Setup
To get started we need to create a folder project and then cd into the folder npm init -y for generating pacakge.json.
We also need to install few Apollo dependencies along with express.
npm i -s apollo-server apollo-core express nodemon
nodemon help us to detect changes and automatically restart server for us.
let's open the folder in VS Code and create a index.js file ( in root directory ) and also create a script in package.json for running the server as follows
//package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon ./index.js"
},
Mock Data
We also have users list which is used to show some mock data create users.js files with following content in the project root.
//users.js
const users =[
{
name:"Dev",
role: "DBA",
id:1
},
{
name:"Jhon Doe",
role: "Admin",
id:2
},
{
name:"Martin",
role: "Dev",
id:3
}
]
module.exports = users;
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.