Ruby GraphQL Boilerplate Code

With the Book model working fine, its time to add GraphQL related files.

Add the graphql gem (specify version 1.8.0 or above for the class based api) and do a bundle install --deployment.

Create a the graphql/types folder and create a Book type in book.rb file. In the graphql folder, create a schema (schema.rb), root query (query.rb). The files look like these:

# File graphql/types/book.rb

require 'graphql'

modules Types
  class Book < GraphQL::Schema::Object
    description 'Resembles a Book'

    field :isbn, String, null: false
    field :title, String, null: false
    field :author, String, null: false
  end
end

In the root query, add the books field for the books query, that will return Book.scan. For aws-record, Book.scan will scan the DynamoDB table and return all records.

Note: `scan` is an expensive DynamoDB operation and its recommended to not use it in production. For simplicity sake, this guide uses scan, instead of using other secondary indices.
# File graphql/query_type.rb

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

class QueryType < GraphQL::Schema::Object
  description "The query root of this schema"

  field :books, [Types::Book], null: false do
    description 'Get all books'
  end

  def books
    Book.scan
  end
end

The schema file will be like below, with the QueryType added to schema.

# File graphql/bookshelf_schema.rb

require 'graphql'
require_relative 'query_type'

class BookshelfSchema < GraphQL::Schema
  query QueryType
end

The schema definition is complete. Now you need to add a graphql handler that will be used to query this schema.

Create a new handler - graphql.rb in the handlers folder with the following contents.

# File handlers/graphql.rb

require 'json'

require_relative '../graphql/schema'

def execute(event:, context:)
  data = JSON.parse(event['body'])

  result = BookshelfSchema.execute(
    data['query'],
    variables: data['variables'],
    context: { current_user: nil },
  )

  {
    statusCode: 200,
    body: JSON.generate(result)
  }
end

In this handler, the GraphQL query and variables that are being sent by the user (obtained by parsing the event['body']) is passed the execute() function of the schema, which retuns a ruby hash of the results.

Add the GraphQL endpoint to serverless.yml

Add the new function in serverless.yml, which maps to the POST path /graphql.

functions:
  hello:
    ...

  graphql:
    handler: handlers/graphql.execute
    events:
      - http:
          path: graphql
          method: post

View the full changes here.

Deploy with serverless deploy and we are ready to go. Note the endpoint created.

Get notified on engineering articles like this

Follow us on twitter @neumeralhq