GraphQL Basic Scenario using Node.js and Express

Clark Johnson
2 min readMar 23, 2020

--

While we’re all locked down and flattening the COVID-19 curve, I decided to expand my experience level a little.

Node.js Setup

This example runs on Node.js. The dependencies necessary to execute are express, expressGraphQL, graphql, axios, lodash, and json-server.

Once the dependencies have been added by way of npm or yarn, utilize GraphQL middleware in server.js with the .use() method.

This will set up our server to listen for requests on port 4000. Our GraphQL server requires a schema object to define its actions.

Schema

The data we retrieve using GraphQL queries is defined using a set of types. In this project, the schema is defined in a separate module, schema.js. The queries are “resolved” by way of HTTP requests to the json-server API.

Data

Creating a sample data file to use is simple. Here’s what db.json could look like.

Json-server will handle REST calls to facilitate the demo.

Starting the node server and navigating to localhost:4000/graphql with render the GraphiQL IDE.

GraphiQL IDE

From here, sample queries against our modest API can be executed.

Example Queries

To begin, let's create a query for the user whose id is “47”.

Query

{
user(id:"47") {
id,
firstName,
age
}
}

Result

{
"data": {
"user": {
"id": "47",
"firstName": "Samantha",
"age": 21
}
}
}

Here’s a nested query that also contains data related to the user’s company.

Query

{
user(id:"47") {
firstName
company {
id,
name,
description
}
}
}

Result

{
"data": {
"user": {
"firstName": "Samantha",
"company": {
"id": "2",
"name": "Google",
"description": "search"
}
}
}
}

--

--

Clark Johnson

Full stack software engineer seeking projects using React, Ruby on Rails, Javascript, when I’m not at a baseball game