GraphQL in Ruby on Rails

GraphQL in Ruby on Rails
Average rating: 0
(0 votes)

Hello! So much noise around GraphQL and Relay. I had a desire to see how this approach is implemented in the Ruby on Rails

First of all, What is GraphQL?
GraphQL – is data query languages.

Here is more information – =)

Lets start coding
First we will create new project, and add two gems – rack-cors – for cross domain request, and graphql – to implement graphQL on rails

#Gemfile
....
gem 'rack-cors', :require => 'rack/cors'
gem 'graphql'
....

Next settings for cors in application.rb

#application.rb
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => 
      end
    end

Create some models for application

Code from migrations:

#migrations
    create_table :blogs do |t|
      t.string :title
      t.string :content
      t.integer :author_id
      t.timestamps null: false
    end

    create_table :authors do |t|
      t.string :name
      t.timestamps null: false
    end

Don`t forget to add a relation in blog.rb

belongs_to :author

Add some data to seeds.rb

10.times do
  Blog.create(title: "title#{rand 100}", content: "content#{rand 100}", author: Author.create(name: "Name#{rand 100}"))
end

Now we must create schema for GraphQL. We will create folder app/graph, inside we will create other folder, which is named ‘types’.
Don`t forget to add this to autoload path in application.rb

#application.rb
config.autoload_paths << Rails.root.join('app', 'graph', 'types')

In this folder you will create custom types. We need to have one type like point of entry.

graph/types/query_type.rb – add _type to the end of name

QueryType = GraphQL::ObjectType.define do
  name "Query"
  description "The query root for this schema"

  field :blog do
    type BlogType
    argument :id, !types.ID
    resolve -> (obj, args, ctx) {
      Blog.find(args)
    }
  end
end

Next step is to define types for each entity.

#graph/types/author_type.rb
AuthorType = GraphQL::ObjectType.define do
  name 'Author'
  description 'Author of Blogs'
  field :name, types.String
end
#graph/types/blog_type.rb
BlogType = GraphQL::ObjectType.define do
  name "Blog"
  description "A Blog"
  field :title, types.String
  field :content, types.String
  field :author do
    type AuthorType
    resolve -> (obj, args, ctx) {
      obj.author
    }
  end
end

Define schema

#graph/types/blog_schema.rb
BlogSchema = GraphQL::Schema.new(query: QueryType)

Define queries controller


class QueriesController < ApplicationController
  def new
  end

  def create
    query_string = params
    query_variables = params || {}
    result = BlogSchema.execute(query_string, variables: query_variables)
    render json: result
  end
end

and route

Rails.application.routes.draw do
  resources :queries, via: 
end

In application controller we need to add “protect_from_forgery with: :null_session”

And now we can try it with Postman or curl

postman

Conclusion: Maybe not that beneficial to use, if the project does not have thousands of users with different api requests such as in fb and vk. The topic is very interesting for the overall development and who knows what will be in vogue in the near future.

Links:

Example was taken from this article
GraphQL Documentation
Gem for GraphQL

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111