Friday, August 24, 2018

How To Setup GraphQL With NodeJs

We know about RESTFul API which has some complexity in different cases, for example nested http request like domain.com/api/user/frinds/positions/companies and also mutiple http requests concurrently which make the server slow down. And of-course chunk of information instead of full model.

To overcome such problems, GraphQL comes which is a query language for API and querying data as runtime.

To setup GraphQL with NodeJs following steps need to be followed:

npm init 

the above command is to initiate NodeJs environment.

npm install --save express express-graphql graphql lodash

through the above command we will install some dependency packages like express for NodeJs server express-graphql the middleware or bridge layer between express and graphql and lodash is for some utility features.

After installing dependency packages above we need to create express server by creating a file named server.js and add code as follows:

const express = require('express');
const expressGraphQL = require('express-graphql');

const app = express();

app.use('/graphql', expressGraphQL({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening');
});

in the above code we have created express nodejs http server to listen the port number 4000 and then bound graphql middleware with expressjs.

No comments:

Post a Comment