A simple tutorial on how to create a GraphQL server powered by Node.js and Express
First create a new Node.js project (if not already set up):
npm init --y
This command createspackage.json
Documents we need to processnpm
.
Install npm packageexpress
,graphql
withexpress-graphql
:
npm install express graphql express-graphql
Createapp.js
File, let's start from the initializationMeansserver:
const express = require('express')
const app = express()
app.listen(3000, () => {
console.log(‘App listening on port 3000’)
})
Now we addexpress-graphql
. This is anMiddleware, We apply it to only one route,/graphql
route:
const express = require('express')
const graphqlHTTP = require('express-graphql')
const app = express()
app.use(’/graphql’, graphqlHTTP())
app.listen(3000, () => {
console.log(‘App listening on port 3000’)
})
We must pass a containingschema
Attribute, which must containSchemadefinition.
We must first define a pattern!
Createschema.js
File, then we first needgraphql
And then useObject deconstruction grammarWe gotGraphQLSchema
,GraphQLObjectType
withGraphQLString
Objects we will need to use soon:
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql
Then we initialize a new definition architecture valueGraphQLSchema
Instance, pass containsquery
property. This attribute is an instance ofGraphQLObjectType
purpose:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
//...
}),
})
module.exports = schema
In this new object, we must specify aname
withfields
parameter. The last attribute is an object, which contains a set of attributes, each attribute corresponding to each field of the schema. In this example, we sethello
site:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world'
},
},
},
}),
})
Thisresolve()
Method returns a stringworld
, Which means when we askhello
Field, we will return the string.
This is completeschema.js
document content:
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: ‘RootQueryType’,
fields: {
hello: {
type: GraphQLString,
resolve() {
return ‘world’
},
},
},
}),
})
module.exports = schema
Now let's go back to ourapp.js
file.
This is what we have:
const express = require('express')
const graphqlHTTP = require('express-graphql')
const app = express()
app.use(’/graphql’, graphqlHTTP())
app.listen(3000, () => {
console.log(‘App listening on port 3000’)
})
We need nowschema.js
file:
const schema = require('./schema.js')
Then add it to the object and pass it tographqlHTTP()
Constructor:
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
})
)
Ok!
Now, we can test it to see if it works. We can useGraphic language, This is a great tool for testing GraphQL API.
It is installed and enabled, we need to pass another attribute tographqlHTTP
Constructor:
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
})
)
Now after you runnode app.js
,accesshttp://localhost:3000/graphql
Using the URL of the browser, you will see the running status of GraphiQL:
You can test the first API call with the following query:
{
hello
}
The results are as follows:
Now let us build a more complex architecture.
One has a nested type.
One example I think of is a blog post.
A blog post has a title, description, and author. The author has a name.
Let us figure this out.
First, we add a set of posts and authors:
const posts = [
{
title: 'First post',
description: 'Content of the first post',
author: 'Flavio',
},
{
title: 'Second post',
description: 'Content of the second post',
author: 'Roger',
},
]
const authors = {
Flavio: {
name: ‘Flavio’,
age: 36,
},
Roger: {
name: ‘Roger’,
age: 7,
},
}
This is where we get data from.
Next, we define 3 GraphQLObjectType
Examples:
authorType
, Which defines the author datapostType
, Which defines the release dataqueryType
, The main
Let's start with the author. The author has a name and age.
We useGraphQLInt
Type, we must add it to require:
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt } = graphql
//…
const authorType = new GraphQLObjectType({
name: ‘Author’,
fields: {
name: {
type: GraphQLString,
},
age: {
type: GraphQLInt,
},
},
})
Next ispostType
. The post has a title, description (two strings) and author. Author typeauthorType
, We just defined it, and there is a parser.
We start fromsource
Parameter, that is, the parameter passed to the post object, and then we find the author data based on the parameter. We return the goods.
const postType = new GraphQLObjectType({
name: 'Post',
fields: {
title: {
type: GraphQLString,
},
description: {
type: GraphQLString,
},
author: {
type: authorType,
resolve: (source, params) => {
return authors[source.author]
},
},
},
})
Note that the resolver function can be asynchronous, so you can use async/await to find resources from the database or the network.
Next is queryType, which is the root type we will add to the schema. In it, we define 2 fields:
post
A single blog post, identified by IDposts
List of posts
They all have a parser function and can be used inposts
Large batch:
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
post: {
type: postType,
args: {
id: { type: GraphQLInt },
},
resolve: (source, { id }) => {
return posts[id]
},
},
posts: {
type: new GraphQLList(postType),
resolve: () => {
return posts
},
},
},
})
Pay attention to the newGraphQLList
Type, we use it to packpostType
Means this is a listpostType
Object. We must first require it:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
} = graphql
That's it. We need to add it to ourschema
And set to:
const schema = new GraphQLSchema({
query: queryType,
})
This is the complete code:
const graphql = require('graphql')
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
} = graphql
const posts = [
{
title: ‘First post’,
description: ‘Content of the first post’,
author: ‘Flavio’,
},
{
title: ‘Second post’,
description: ‘Content of the second post’,
author: ‘Roger’,
},
]
const authors = {
Flavio: {
name: ‘Flavio’,
age: 36,
},
Roger: {
name: ‘Roger’,
age: 7,
},
}
const authorType = new GraphQLObjectType({
name: ‘Author’,
fields: {
name: {
type: GraphQLString,
},
age: {
type: GraphQLInt,
},
},
})
const postType = new GraphQLObjectType({
name: ‘Post’,
fields: {
title: {
type: GraphQLString,
},
description: {
type: GraphQLString,
},
author: {
type: authorType,
resolve: (source, params) => {
return authors[source.author]
},
},
},
})
const queryType = new GraphQLObjectType({
name: ‘Query’,
fields: {
post: {
type: postType,
args: {
id: { type: GraphQLInt },
},
resolve: (source, { id }) => {
return posts[id]
},
},
posts: {
type: new GraphQLList(postType),
resolve: () => {
return posts
},
},
},
})
const schema = new GraphQLSchema({
query: queryType,
})
module.exports = schema
View the complete code about the failure.
More graphql tutorials:
- Introduction to GraphQL
- A complete introduction to the GraphQL toolkit Apollo
- How to create a GraphQL server using Node.js and Express
- How to use GraphQL Cookies and JWT for authentication
- GraphQL API and REST API