Build a GraphQL Server CRUD API in Node.js and Express Using Express-GraphQL Library Full Project For Beginners

You are currently viewing Build a GraphQL Server CRUD API in Node.js and Express Using Express-GraphQL Library Full Project For Beginners

 

 

 

Welcome folks today in this blog post we will be making a graphql server in which we will handling crud operations in the form of api. We will be using node.js and express for this purpose. All the source code of the project will be given below.

 

 

 

Get Started

 

 

 

In order to get started we need to install the following dependencies

 

First of all we need to initialize the empty node.js project by executing the following commands

 

npm init -y

 

After that we need to install the following dependencies

 

npm i express

 

npm i nodemon

 

npm i graphql

 

npm i express-graphql

 

So here we are installing first of all express library for constructing our http server inside the node.js application

And after that we will be installing nodemon library to automatically restart the application for us.

And then we are installing the graphql library for making the graphql api

And now we are installing the express-graphql library for using graphql with express.

After installing all these dependencies you will find the package.json file and all the dependencies will be contained inside the file.

Now you need to make a index.js file and copy paste the following code

 

index.js

 

 

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

const app = express()

app.use('/graphql', graphqlHTTP({
  graphiql: true
}))
app.listen(5000, () => console.log('Server Running'))

 

 

Here you can see we have imported the express library and also express-graphql. Here we have initialized a simple express app at port 5000. And also we have initialized a special middleware function to the route /graphql and we have passed a option graphiql to true.

 

And now if you execute the application you will see a error of schema like this

 

 

 

 

As you can see graphql middleware must contain a schema. Schema is actually the data which the graphql server will be returning when you make a request to it.

 

Now we need to define our data inside our application or schema to be precise.

 

var Owners = [
    { id: 1, name: 'John Astle' },
    { id: 2, name: 'Gautam Sharma' },
    { id: 3, name: 'Kane Williamson' }
]

var Websites = [
    { id: 1, name: 'Facebook', ownerId: 1 },
    { id: 2, name: 'Google', ownerId: 2 },
    { id: 3, name: 'Amazon', ownerId: 3 },
    { id: 4, name: 'Github', ownerId: 1 },
    { id: 5, name: 'Medium', ownerId: 2 },
    { id: 6, name: 'Baidu', ownerId: 3 },
    { id: 7, name: 'Zapak', ownerId: 1 },
    { id: 8, name: 'Cricinfo', ownerId: 2 }
]

 

 

So you can see that we have two arrays namely websites and owners. For Simplicity we are taking static arrays you can also take database as well.

 

And now we define the fields which are there inside the arrays first we will tackle website array as you can see there are three fields out there id and name and ownerID

Inside the index.js file copy paste the following code

 

 

const WebsiteType = new GraphQLObjectType({
  name: 'Website',
  description: 'This represents a website made by a Owner(Programmer)',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    ownerId: { type: GraphQLNonNull(GraphQLInt) },
  })
})

 

 

So here in the above code we have defined a variable called as WebsiteType which stores the actual object type of Website Arrays and here we are using name and description, and fields. Inside fields we have defined id, name and ownerID

 

For this we need to import GraphQLINT , GraphQLString and GraphQLNonNull from the graphql library as shown below.

 

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

 

 

Similarly we will define Owners Array Object type called as OwnerType as shown below

 

const OwnerType = new GraphQLObjectType({
  name: 'Owner',
  description: 'This represents a owner of a website',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
  })
})

 

 

 

Now we will define the queries that we will make to the GraphQL Server as shown below

 

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    websites: {
      type: new GraphQLList(WebsiteType),
      description: 'List of All Websites',
      resolve: () => Websites
    },
    owners: {
      type: new GraphQLList(OwnerType),
      description: 'List of All Owners',
      resolve: () => Owners
    }
  })
})

 

 

So these two queries will return the list of websites and owners

 

Now we will be importing the GraphQLList from graphql

 

const {
  GraphQLList
} = require('graphql')

 

 

So now lastly we will define the schema inside our application like this

 

const schema = new GraphQLSchema({
  query: RootQueryType
})

 

 

So we will import the GraphQLSchema from graphql

 

const {
  GraphQLSchema
} = require('graphql')

 

 

Now if you run the node application by running the following command

 

node index.js

 

And now if you go to this route localhost:5000/graphql

 

 

 

 

So you can see we have executed the below query inside the graphql server

 

{
websites{
name
}
}

 

 

So you can also tweak this query by adding more fields like this to this query

 

{
websites{
id
name
ownerId
}
}

 

 

 

 

 

As we query owners you will see the following image

 

 

 

Now we will query a single website and single owner like this

 

fields: () => ({
    website: {
      type: WebsiteType,
      description: 'A Single Website',
      args: {
        id: { type: GraphQLInt }
      },
      resolve: (parent, args) => Websites.find(website => website.id === args.id)
    },
    owner: {
      type: OwnerType,
      description: 'A Single Owner',
      args: {
        id: { type: GraphQLInt }
      },
      resolve: (parent, args) => Owners.find(owner => owner.id === args.id)
    }

 

 

Now if you execute the app and now to retrieve a single website or owner

 

{
  website(id:1){
    name
    ownerId
  }
}

 

 

 

 

 

Mutations in GraphQL Server

 

 

Now guys we will look at the very important concept of mutations which is  crud operations which is creation, deletion and updation

 

For this you need to add this code

 

const RootMutationType = new GraphQLObjectType({
  name: 'Mutation',
  description: 'Root Mutation',
  fields: () => ({
    addWebsite: {
      type: WebsiteType,
      description: 'Add a website',
      args: {
        name: { type: GraphQLNonNull(GraphQLString) },
        ownerId: { type: GraphQLNonNull(GraphQLInt) }
      },
      resolve: (parent, args) => {
        const website = { id: Websites.length + 1, name: args.name,ownerId:args.ownerId }
        Websites.push(website)
        return website
      }
    },
    removeWebsite: {
        type: WebsiteType,
        description: 'Remove a Website',
        args: {
          id: { type: new GraphQLNonNull(GraphQLInt) }
        },
        resolve: (parent, args) => {
            Websites = Websites.filter(website => website.id !== args.id)
            return Websites[args.id]
        }
      },
    addOwner: {
      type: OwnerType,
      description: 'Add an Owner',
      args: {
        name: { type: GraphQLNonNull(GraphQLString) }
      },
      resolve: (parent, args) => {
        const owner = { id: Owners.length + 1, name: args.name }
        Owners.push(owner)
        return owner
      }
    },
    removeOwner: {
        type: OwnerType,
        description: 'Remove an Owner',
        args: {
          id: { type: new GraphQLNonNull(GraphQLInt) }
        },
        resolve: (parent, args) => {
            Owners = Owners.filter(owner => owner.id !== args.id)
            return Owners[args.id]
        }
      },
      updateOwner: {
        type: OwnerType,
        description: 'Update an Owner',
        args: {
          id: { type: new GraphQLNonNull(GraphQLInt) },
          name:{type:new GraphQLNonNull(GraphQLString)}
        },
        resolve: (parent, args) => {
            Owners[args.id - 1].name = args.name
            return Owners[args.id - 1]
        }
      },
      updateWebsite: {
        type: WebsiteType,
        description: 'Update a Website',
        args: {
          id: { type: new GraphQLNonNull(GraphQLInt) },
          name:{type:new GraphQLNonNull(GraphQLString)},
          ownerId:{type:new GraphQLNonNull(GraphQLInt)}
        },
        resolve: (parent, args) => {
            Websites[args.id - 1].name = args.name
            Websites[args.id - 1].ownerId = args.ownerId
            return Websites[args.id - 1]
        }
      },
  })
})

 

 

 

So now after this we need to add a special attribute called as mutation inside schema variable

 

const schema = new GraphQLSchema({
    query: RootQueryType,
    mutation: RootMutationType
  })

 

 

 

Now if you execute this query to add a owner like this

 

mutation{
  addOwner(name:"john henry"){
    name
    id
  }
}

 

 

 

 

 

Now if you check the no of owners like this

 

 

 

 

Now in order to update the website we will write the query like this

 

 

mutation{
  updateWebsite(id:1,name:"facebook1",ownerId:3){
    name
    id
    ownerId
  }
}

 

 

 

 

Now to Delete the website we will write the query

 

 

mutation{
  removeWebsite(id:1){
    name
    id
  }
}

 

 

 

 

 

 

 

 

 

Leave a Reply