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 =
        title: title,
        author: author,
        isbn: isbn

          success: true,
          errors: []
          success: false,
          errors: ['Cannot save the book']

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

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

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