...

/

Running GraphQL using NodeJS

Running GraphQL using NodeJS

NodeJS

In this lesson we will setup Docker Job for NodeJS.

Press + to interact
// Importing the required libraries
var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');
// Building Schema of GraphQL API
var schema = buildSchema(`
type Query {
hello: String
}
`);
// Creating a function to call in API
var root = { hello: () => 'Hello world!' };
// Running GraphQL on Express server
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
// Assigning the port where it will listen
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));

Docker Job

Let’s see what each field in the above job means:

Select Docker Job Type

This is Docker Job Type selection in which we have to select what kind of docker job we are creating.

Live

Job Name

This is just a job name for reference. You can use any name you want to specify for this job.

NodeDockerJob

Input File Name

Name of the input file you want to run in code widget. In our case, it is server.js.

server.js

Run Script

This script runs when we execute the code in the code widget. It is mandatory.

node server.js

Application Port

We have to specify the port on which we want to run it.

4000

Start Script

This script runs when we execute the Live Widget for the very first time. It is mandatory.

cp server.js /usercode && node server.js

Now that our Node Express Server environment is all set up, we can make a SPA widget, and select the job name set for NodeDockerJob as illustrated below:

Select a Docker Job

Overriding Entry Point

Let’s run an example

var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = { hello: () => 'Hello world!' };

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));

Code Breakdown

From Lines 1-3 we are importing the required libraries to run GraphQL server.

From Lines 5-9 we are building a schema.

On Line 11 we wrote a query against which we will be fetching data.

From Lines 13-19 we are running GraphQL server.

Access this course and 1200+ top-rated courses and projects.