Slide 1

Slide 1 text

Vipul A M GRAPHQL BEYOND REST

Slide 2

Slide 2 text

@vipulnsward Saeloun

Slide 3

Slide 3 text

https://blog.saeloun.com/

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Kyoto Typhoon last year

Slide 6

Slide 6 text

Alaska 7.2 Earthquake from 9th Floor

Slide 7

Slide 7 text

NY Manhattan Blackout

Slide 8

Slide 8 text

Stabbings in Singapore

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

10

Slide 11

Slide 11 text

GRAPHQL

Slide 12

Slide 12 text

-2012/2015 -N+1 HTTP Queries -Under/Over querying -Versioning

Slide 13

Slide 13 text

-Supporting Multiple Apis:
 api/v1, api/mobile, api/v2
 api/v42?, etc

Slide 14

Slide 14 text

QUICK TOUR

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

BEFORE

Slide 20

Slide 20 text

GRAPHQL RUBY

Slide 21

Slide 21 text

-Schema -Queries -Mutations -Subscriptions

Slide 22

Slide 22 text

# Add graphql-ruby boilerplate and mount graphiql in development rails g graphql:install # Make your first object type rails g graphql:object Post title:String rating:Int comments:[Comment]

Slide 23

Slide 23 text

# app/graphql/types/post_type.rb class Types::PostType < Types::BaseObject field :id, ID, null: false field :title, String, null: false field :truncated_preview, String, null: false field :comments, [Types::CommentType], null: true end

Slide 24

Slide 24 text

class QueryType < GraphQL::Schema::Object description "The query root of this schema" # First describe the field signature: field :post, PostType, null: true do description "Find a post by ID" argument :id, ID, required: true end # Then provide an implementation: def post(id:) Post.find(id) end end

Slide 25

Slide 25 text

class Schema < GraphQL::Schema query QueryType end

Slide 26

Slide 26 text

query_string = " { post(id: 1) { id title truncatedPreview } }" result_hash = Schema.execute(query_string) # { # "data" => { # "post" => { # "id" => 1, # "title" => "GraphQL is nice" # "truncatedPreview" => "GraphQL is..." # } # } # }

Slide 27

Slide 27 text

SCHEMA / TYPES

Slide 28

Slide 28 text

type User { email: String handle: String! friends: [User!]! } GraphQL Schema Definition Language(SDL)

Slide 29

Slide 29 text

class Types::User < GraphQL::Schema::Object field :email, String, null: true field :handle, String, null: false field :friends, [User], null: false end

Slide 30

Slide 30 text

class Types::TodoList < Types::BaseObject field :name, String, null: false field :is_completed, String, null: false # Related Object: field :owner, Types::User, null: false # List field: field :viewers, [Types::User], null: false # Connection/for pagination-relay: field :items, Types::TodoItem.connection_type, null: false do argument :status, TodoStatus, required: false end end

Slide 31

Slide 31 text

class ChangelogSchema < GraphQL::Schema mutation(Types::MutationType) query(Types::QueryType) end

Slide 32

Slide 32 text

SCALAR field :name, String field :top_score, Integer, null: false field :avg_points_per_game, Float, null: false field :is_top_ranked, Boolean, null: false field :id, ID, null: false field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :parameters, GraphQL::Types::JSON, null: false CustomScalars

Slide 33

Slide 33 text

ENUMS class Types::MediaCategory < Types::BaseEnum value "AUDIO", "An audio file, such as music or spoken word" value "IMAGE", "A still image, such as a photo or graphic" value "TEXT", "Written words" value "VIDEO", "Motion picture, may have audio" end

Slide 34

Slide 34 text

LISTS argument :categories, [Types::PostCategory], required: false field :previous_employers, [Types::Employer, null: true], null: false

Slide 35

Slide 35 text

-Input Objects -Interfaces -Unions -Directives

Slide 36

Slide 36 text

QUERIES

Slide 37

Slide 37 text

query_string = "{ ... }" MySchema.execute(query_string) # { # "data" => { ... } # }

Slide 38

Slide 38 text

MySchema.multiplex([ {query: query_string_1}, {query: query_string_2}, {query: query_string_3}, ]) # [ # { "data" => { ... } }, # { "data" => { ... } }, # { "data" => { ... } }, # ]

Slide 39

Slide 39 text

context = { current_user: current_user, routes: Rails.application.routes.url_helpers, } query_string = "{ ... }" MySchema.execute(query_string, context: context) # { # "data" => { ... } # }

Slide 40

Slide 40 text

query_string = " query getPost($postId: ID!) { post(id: $postId) { title } }" variables = { "postId" => "1" } MySchema.execute(query_string, variables: variables)

Slide 41

Slide 41 text

-root_value -operation_name -max_depth -max_complexity

Slide 42

Slide 42 text

class Queries::Commit::Detail < Queries::BaseResolver type Types::CommitType, null: false argument :id, String, required: true def resolve(id:) Commit.find(id) rescue ActiveRecord::RecordNotFound => error GraphQL::ExecutionError.new(error.message) end end

Slide 43

Slide 43 text

MUTATIONS

Slide 44

Slide 44 text

class Schema < GraphQL::Schema # ... mutation(Types::Mutation) end

Slide 45

Slide 45 text

-CRUD -Controller level operations -Session Management -File Creations, etc

Slide 46

Slide 46 text

class Mutations::PublishCommit < Mutations::BaseMutation type Types::MutationResponseType argument :id, String, required: true argument :body, String, required: false def resolve(id:, body: nil) commit = Commit.find(id) create_or_update_post(body, commit) if body.present? commit.published! commit rescue ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid => error GraphQL::ExecutionError.new(error.message) end private def create_or_update_post(body, commit) post = Post.find_or_initialize_by(commit_id: commit.id) post.update body: body end end

Slide 47

Slide 47 text

SUBSCRIPTIONS VIA ACTION CABLE

Slide 48

Slide 48 text

VALIDATION -Client side validation -Server Query validation -Demo

Slide 49

Slide 49 text

ERROR HANDLING -Query Validation Errors -Invariants: null fields, union/interface

Slide 50

Slide 50 text

class Mutations::PublishCommit < Mutations::BaseMutation ... def resolve(id:, body: nil) commit = Commit.find(id) create_or_update_post(body, commit) if body.present? commit.published! commit rescue ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid => error raise GraphQL::ExecutionError.new(error.message) # OR raise GraphQL::ExecutionError.new(commit.full_messages.join(", ")) end end

Slide 51

Slide 51 text

class Types::UserError < Types::BaseObject field :message, String, null: false field :path, [String], null: true end
 class Mutations::UpdatePost < Mutations::BaseMutation # ... field :errors, [Types::UserError], null: false end


Slide 52

Slide 52 text

def resolve(id:, attributes:) post = Post.find(id) if post.update(attributes) { post: post, errors: [], } else # Convert Rails model errors into GraphQL-ready error hashes user_errors = post.errors.map do |attribute, message| path = ["attributes", attribute.camelize] { path: path, message: message, } end { post: post, errors: user_errors, } end end

Slide 53

Slide 53 text

class ChangelogSchema < GraphQL::Schema ... rescue_from(ActiveRecord::NotFound) do |err, obj, args, ctx, field| # Raise a graphql-friendly error with a custom message raise GraphQL::ExecutionError, "#{field.type.unwrap.graphql_name} not found" end end

Slide 54

Slide 54 text

INTROSPECTION -Demo -Visibility(Types/Mutations, etc) -Schema Driven Development

Slide 55

Slide 55 text

LAZY EXECUTION -Object Store -shopify/graphql-batch -exAspArk/batch-loader -@defer

Slide 56

Slide 56 text

class LazyFindPerson def initialize(query_ctx, person_id) @person_id = person_id @lazy_state = query_ctx[:lazy_find_person] ||= { pending_ids: Set.new, loaded_ids: {}, } @lazy_state[:pending_ids] << person_id end def person loaded_record = @lazy_state[:loaded_ids][@person_id] if loaded_record loaded_record else pending_ids = @lazy_state[:pending_ids].to_a people = Person.where(id: pending_ids) people.each { |person| @lazy_state[:loaded_ids][person.id] = person } @lazy_state[:pending_ids].clear @lazy_state[:loaded_ids][@person_id] end end end

Slide 57

Slide 57 text

class MySchema < GraphQL::Schema # ... lazy_resolve(LazyFindPerson, :person) end field :author, PersonType, null: true def author LazyFindPerson.new(context, object.author_id) end 
 
 { p1: post(id: 1) { author { name } } p2: post(id: 2) { author { name } } p3: post(id: 3) { author { name } } }

Slide 58

Slide 58 text

BATCHING -Client side: Demo -Multiplex -Dataloader

Slide 59

Slide 59 text

CACHING -GraphQL preference: id, __typename -InMemoryStore in Apollo -Rails.cache -stackshareio/graphql-cache (easy caching on models) -CDN Caching(Akamai, etc)

Slide 60

Slide 60 text

VERSIONING

Slide 61

Slide 61 text

field :author_name, String, deprecation_reason: "Commit author can now be accessed as an Object", null: false DEPRECATIONS

Slide 62

Slide 62 text

CONSIDERATIONS -JSON with GZIP -Pagination

Slide 63

Slide 63 text

TRANSITION -Use Both: REST for Auth /
 GraphQL -apollo-link-rest

Slide 64

Slide 64 text

THANK YOU https://speakerdeck.com/vipulnsward/beyond-rest-graphql-in-ruby-on-rails