Mutations

To create a book, you need to add create_book mutation in GraphQL. In the graphql/mutations folder add a new file create_book.rb, which will take all the three fields as arguments. The resolve function will get the arguments and save the book to DynamoDB. Returns the json fields success and errors.

# File graphql/mutations/create_book.rb

require 'graphql'
require_relative '../../models/book'

module Mutations
  class CreateBook < GraphQL::Schema::Mutation
    description 'Creates a Book'

    argument :title, String, required: true
    argument :isbn, String, required: true
    argument :author, String, required: true

    field :success, Boolean, null: false
    field :errors, [String], null: false

    def resolve(name:, bio:, twitter_handle:, talk_title:)

      book = Book.new(
        title: title,
        author: author,
        isbn: isbn
      )

      if book.save!
        {
          success: true,
          errors: []
        }
      else
        {
          success: false,
          errors: ['Cannot save the book']
        }
      end
    end
  end
end

Add a root mutation.

require 'graphql'
require_relative 'mutations/create_book'

class MutationType < GraphQL::Schema::Object
  description "The mutation root of this schema"

  field :createBook, mutation: Mutations::CreateBook
end

And then add it to the schema.

require 'graphql'
require_relative 'query_type'
require_relative 'mutation_type'

class BookshelfSchema < GraphQL::Schema
  query QueryType
  mutation MutationType
end

For more on GraphQL mutations read this.

Deploy to AWS Lambda, and you can run the following mutation.

GraphQL Mutation

This will save the book in the table, and show a successful message.

That’s it. You now have a fully functional GraphQL endpoint, running on serverless AWS Lambda!

Get notified on engineering articles like this

Follow us on twitter @neumeralhq