This blogs aims to help you setup GraphQL with NodeJS from scratch and help you make your own starter kit.

GraphQL is a very powerful query language used to communicate data between client and server.

  • It allows more flexible & efficient approach than REST.
  • No more Over- and Underfetching
  • Benefits of a Schema & Type System
  • Rapid Product Iterations on the Frontend
  • GraphQL is platform independent

Pre-requisites

  • Initial knowledge of GraphQL
  • NPM 6.2.0
  • Node v8+

Creating GraphQL server on NodeJS using express

  • We will setup entry point to the graph in NodeJS.

Go to your terminal application

create a new directory

mkdir graphql_proj

then move inside that directory

cd graphql_proj

Initiate a project using NPM which will create package.json used for our dependency management.

npm init

answer all sort of questions like name of project, version, author, keywords, once done you would observe a package.json file inside the graphql_proj directory

Now lets installed our required dependencies

sudo npm install express --save

create express server

create a file inside graphql_proj directory named app.js and use the following code to make your express server up and running

const express = require('express');

const app = express();

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

and run using node command

node app.js

You should see "Listening to 4000" on your terminal.

Now lets setup GraphQL with this application

Install graphql and express-graphql for running GraphQL on our express server

sudo npm install graphql express-graphql

once the dependencies are installed, we will setup an endpoint for graphQL using which client can interact to our GraphQL server.

const express = require('express');

//allows express to understand graphql
const graphqlHTTP = require('express-graphql');

//initiate express
const app = express();

//setup middleware and graphqlHTTP handle graphql request
app.use('/graphql', graphqlHTTP({

}));

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

now if we open browser and goto localhost:4000/graphql, it gives

{"errors":[{"message":"GraphQL middleware options must contain a schema."}]}

to fix this error we will define the schema for our middleware function

Lets create our schema in  in our schema directory

i.e graphql_proj/schema/schema.js

We use loadash a commonly used library for data structure manipulation and operations.

const graphql = require('graphql');
const {GraphQLObjectType, GraphQLString, GraphQLSchema} = graphql;

const _ = require('loadash');


//schema defines the object types and relation b/w object types
//so the graph will have vehicles and car-manufacturers as object types

//dummy data
const vehicles = [
    {name: 'Jeep Compass', type: 'SUV', id: '1'},
    {name: 'Mercedes-Benz A-Class', type: 'Hatchback', id: '2'},
    {name: 'Mercedes S class', type: 'Sedan', id: '3'}
];

const VehicleType = new GraphQLObjectType({
    name: 'Vehicle', //name of the object type
    fields: () => ({ //use function as will have multiple types
        id: {type: GraphQLString},
        name: {type: GraphQLString},
        type: {type: GraphQLString}
    })
});


const RootQuery = new GraphQLObjectType({ //how we can jump into graph
    name: 'RootQueryType',
    fields: {
        /* name of the query used
         when requested from graphiql */
        vehicle: {
            type: VehicleType,
            args: {id: {type: GraphQLString}},
            resolve(parent, args) {
                /*this is where we can place our code
                 get data from db or APIs in real scenerio*/
                return _.find(vehicles, {id: args.id});
            }
        }
    }
});

/*query for vehicle
    vehicle(id:"2") {
        name,
        type
    }
 */


module.exports = new GraphQLSchema({
    query: RootQuery
});

and now graphql_proj/app.js becomes

const express = require('express');
const schema  = require('./schema/schema');
//allows express to understand graphql
const graphqlHTTP = require('express-graphql');

//initiate express
const app = express();

//setup middleware and graphqlHTTP handle graphql request
app.use('/graphql', graphqlHTTP({
    schema : schema
}));


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

Now setting up graphiql (GraphQL client interface) in graphql_proj/app.js

const express = require('express');
const schema  = require('./schema/schema');
//allows express to understand graphql
const graphqlHTTP = require('express-graphql');

//initiate express
const app = express();

//setup middleware and graphqlHTTP handle graphql request
app.use('/graphql', graphqlHTTP({
    schema : schema,
    graphiql: true //this is used to
}));


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

Now go to browser and you will see graphiql up and running at http://localhost:4000/graphql

Now paste the following query on left side of graphiql GUI to see the result

vehicle(id:"2") {
	name,
	type
}

I hope you enjoyed this blog.