How to create a GraphQL server using Node.js and Express

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.jsonDocuments we need to processnpm.

Install npm packageexpress,graphqlwithexpress-graphql:

npm install express graphql express-graphql

Createapp.jsFile, 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,/graphqlroute:

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 containingschemaAttribute, which must containSchemadefinition.

We must first define a pattern!

Createschema.jsFile, then we first needgraphqlAnd then useObject deconstruction grammarWe gotGraphQLSchema,GraphQLObjectTypewithGraphQLStringObjects we will need to use soon:

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

Then we initialize a new definition architecture valueGraphQLSchemaInstance, pass containsqueryproperty. This attribute is an instance ofGraphQLObjectTypepurpose:

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    //...
  }),
})

module.exports = schema

In this new object, we must specify anamewithfieldsparameter. 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 sethellosite:

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 askhelloField, we will return the string.

This is completeschema.jsdocument 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.jsfile.

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.jsfile:

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 tographqlHTTPConstructor:

app.use(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    graphiql: true,
  })
)

Now after you runnode app.js,accesshttp://localhost:3000/graphqlUsing 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 GraphQLObjectTypeExamples:

  • authorType, Which defines the author data
  • postType, Which defines the release data
  • queryType, The main

Let's start with the author. The author has a name and age.

We useGraphQLIntType, 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 fromsourceParameter, 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:

  • postA single blog post, identified by ID
  • postsList of posts

They all have a parser function and can be used inpostsLarge 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 newGraphQLListType, we use it to packpostTypeMeans this is a listpostTypeObject. We must first require it:

const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
} = graphql

That's it. We need to add it to ourschemaAnd 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: