GraphQL

Rest API

  • Posts
    • '/posts'
    • '/posts/1'
  • Posts with comments
    • '/posts_with_comments'
    • '/posts?with_comments=true'
  • Comments
    • '/post/1/comments'
# PostsController.rb
def index
    Post.all
end

def post_with_comments
    Post.include(:comments).all
end

def show
    Post.find(params[:id])
end

Rest API

  • Wymaga sprawdzania dokumentacji czego możemy się spodziewać w response 
  • Zwracamy większe ilości danych przy każdym requeście w celu zmniejszenia ilości metod w kontrolerach

GraphQL

GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine.

GraphQL

GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine.

GraphQL

  1. Define types

  2. Define queries/schema

  3. Mount query endpoint

Define types

CommentType = GraphQL::ObjectType.define do
    name 'Comment'
    description 'A blog post comment'

    field :id, !types.ID
    field :author, !types.String
    field :content, !types.String
end

PostType = GraphQL::ObjectType.define do
    name 'Post'
    description 'A blog post'

    field :id, !types.ID
    field :title, !types.String
    field :body, !types.String
    field :comments, types[!CommentType]
end

Define schema

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

  field :allPosts do
    type types[PostType]
    resolve ->(_obj, args, _ctx) { Post.all }
  end

  field :post do
    type PostType
    argument :id, !types.ID
    resolve ->(_obj, args, _ctx) { Post.find(args['id']) }
  end
end


Schema = GraphQL::Schema.define do
  query QueryType
end

Mount query endpoint

class GraphqlController < ApplicationController
  def query
    query_string = params[:query]
    render json: Schema.execute(query_string)
  end
end

GraphQL

  • Dostajemy to czego oczekujemy ( albo error)
  • Schema tworzy nam "dokumentacje" API

GraphQL

By vrael560

GraphQL

  • 411