GraphQL

Build GraphQL CRUD API in Node & Express Server from Scratch – Part 2

January 29, 2018

author:

Build GraphQL CRUD API in Node & Express Server from Scratch – Part 2

In the last segment, we worked on create and insert operation for our GraphQL API. We also tested both operations properly. In this one, without wasting much time, we will continue from where we left..

Update Operation in GraphQL:

# GraphQL Type to Update Object

For update operation in our GraphQL API, lets define BookUpdateType with relevant properties. As earlier, we will use BookType as a type here:

# src/graphql/types.js
...
const BookType = new GraphQLObjectType({
    ...
});

const BookCreateType = new GraphQLInputObjectType({
    ...
});

const BookUpdateType = new GraphQLInputObjectType({
    name: 'BookUpdateType',
    description: 'Update existing book with id',
    type: BookType,
    fields: {
        id: { type: new GraphQLNonNull(GraphQLString) },
        name: { type: new GraphQLNonNull(GraphQLString) },
        author: { type: new GraphQLNonNull(GraphQLString) }
    }
});

module.exports = {
    ...
    BookUpdateType
}

Since the user has to determine data for which id it wants to update, we also mentioned id in the required fields.

# Mutation type for update

Let us wire the BookUpdateType with new updateBook mutation:

# src/graphql/types.js
...
const {
    ...
    BookUpdateType
} = require('./types.js');

...

const BookMutationType = new GraphQLObjectType({
    ...
    fields: {
        createBook: {
            ...
        },
        updateBook: {
            type: BookType,
            args: {
                input: { type: new GraphQLNonNull(BookUpdateType) }
            },
            resolve: (source, { input }) => {
                let book = [];
                book.id = input.id;
                book.name = input.name;
                book.author = input.author;

                let findId = Books.findIndex(b => b.id == input.id);
                let update = Books.splice(findId, 1, book);

                return book;
            }
        }
    }
});
...

We are utilizing BookUpdateType as a required input parameter in args. Since mutation should have only a single argument and must be GraphQLNonNull type, we are using a generic name input to hold all our arguments in BookUpdate type and passing it in the args. This helps to keep code clean as opposed to passing 10 different input arguments.

In the resolve attribute, we are initiating a fresh array and defining its properties with the user inputted data. And then we replace the old array with the new one.

Since we have already wired root mutation in the schema, we don’t need to make any changes there.

# Test GraphQL Update Operation

Let us quickly test the update operation:

node server.js

Test the below mutation in GraphiQL:

http://localhost:8080
mutation updateExistingBook {
  updateBook(input: 
    {
      id: "e7a2dfa2-8532-40e8-9211-71f952736d42", 
      name: "book name goes here",
      author: "book author"
    }) 
  {
    name
    author
  }
}
GraphQL CRUD Update Mutation

Delete Operation in GraphQL:

# GraphQL Type to Delete Object

We can define BookDeleteType that will take care of delete operation in graphQL. As for deleting, our API requires only id of the book to be deleted:

# src/graphql/types.js
...

const BookUpdateType = new GraphQLInputObjectType({
    ...
});

const BookDeleteType = new GraphQLInputObjectType({
    name: 'BookDeleteType',
    description: 'Delete existing book with id',
    type: BookType,
    fields: {
        id: { type: new GraphQLNonNull(GraphQLString) }
    }
});

module.exports = {
    ...
    BookDeleteType
}

# Mutation type for update

It’s time to use the BookDeleteType with a mutation:

# src/graphql/mutations.js
...
const _ = require("lodash");

const {
    ...
    BookDeleteType
} = require('./types.js');


const BookMutationType = new GraphQLObjectType({
    name: 'BookMutationType',
    description: 'Mutations for BookType',
    fields: {
        createBook: {
            ...
        },
        updateBook: {
            ...
        },
        deleteBook: {
            type: BookType,
            args: {
                input: { type: new GraphQLNonNull(BookDeleteType) }
            },
            resolve: (source, { input }) => {
                let deleteBook = _.remove(Books, book => book.id == input.id)
                return input;
            }
        }
    }
});

...

In resolve attribute, we are using remove method of the lodash library (that we installed earlier) to delete the specific record from our file.

Since we have already wired root mutation in the schema, we don’t need to make any changes there.

# Test GraphQL Delete Operation

Let us now test the delete operation:

node server.js

Test the below mutation in GraphiQL. As returning some field in the payload is required, we will return the deleted id:

http://localhost:3000
mutation deleteExistingBook {
  deleteBook(input: {id: "e7a2dfa2-8532-40e8-9211-71f952736d42"}) {
    id
  }
}
GraphQL CRUD Delete Mutation

# GraphQL CRUD API at a glance

Once you understand the basic working of each operation, you can of course tweak the working as required. Also, in this section, we haven’t used any actual DB like MySQL or MongoDB to keep ourselves purely focused on GraphQL. To keep the things at par on both the side, here’s a list of CRUD operation (that we already performed in GraphiQL):

GraphQL Create Operation:

mutation createNewBook {
  createBook(input: {
    name: "The Underground Railroad",
    author: "Colson Whitehead"
  }) {
    id
    name
    author
  }
}

GraphQL Read Operation:

query getAllBooks {
  books {
    id
    name
    author
  }
}

GraphQL Update Operation:

mutation updateExistingBook {
  updateBook(input: 
    {
      id: "e7a2dfa2-8532-40e8-9211-71f952736d42", 
      name: "book name goes here",
      author: "book author"
    }) 
  {
    name
    author
  }
}

GraphQL Delete Operation:

mutation deleteExistingBook {
  deleteBook(input: {id: "e7a2dfa2-8532-40e8-9211-71f952736d42"}) {
    id
  }
}

Conclusion:

Phew! That was some coding. In this tutorial, we created a complete GraphQL API in Node Server. We particularly took care of GraphQL Mutations for Update and Delete operation.

Questions or Comments:

Hope you enjoyed working with CRUD operations in GraphQL as much as I did explaining it. If you still face any issues, reach back to us in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *