# PostsController.rb
def index
Post.all
end
def post_with_comments
Post.include(:comments).all
end
def show
Post.find(params[:id])
end
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 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.
Define types
Define queries/schema
Mount query endpoint
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
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
class GraphqlController < ApplicationController
def query
query_string = params[:query]
render json: Schema.execute(query_string)
end
end