How to Implement GraphQL in Node.js?

Forums Node.jsHow to Implement GraphQL in Node.js?
Staff asked 2 years ago

Answers (1)

Add Answer
Rajbir Marked As Accepted
Staff answered 2 years ago

To create a new project and install GraphQL.js in your current directory:

npm init
npm install graphql --save

 

Writing Code

To handle the GraphQL queries we need a schema that defines the Query type & we need an API root with a function called a ‘resolver’ for each API endpoint . For an API that just returns ' Hello India! ', we can just put this code in a file named server.js:

 

var { graphql, buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The rootValue provides a resolver function for each API endpoint
var rootValue = {
  hello: () => {
    return 'Hello India!';
  },
};

// Run the GraphQL query '{ hello }' and print out the response
graphql({
  schema,
  source: '{ hello }',
  rootValue
}).then((response) => {
  console.log(response);
});

If you run this with:

node index.js

 

You should see the GraphQL response:

{ data: { hello: 'Hello India!' } }

 

Subscribe

Select Categories