Ruby graphql-ruby: Difference between revisions

From wikinotes
Line 92: Line 92:
</source>
</source>
</blockquote><!-- Mutations -->
</blockquote><!-- Mutations -->
== Connections ==
<blockquote>
Connections between nodes are expressed as edges.<br>
Edges can be abstracted as connections to support query params, filters, pagination, etc.<br>
See https://graphql-ruby.org/relay/connections.html
<source lang="ruby">
# Defines a `ClassType`, with the connection `StudentType`.
class ClassType < GraphQL::Schema::Object
  field :students, StudentConnectionType,
    connection: true,
    description: "Students that belong to a class"
end
class StudentConnectionType < GraphQL::Types::Relay::BaseConnection
  edge_type StudentEdgeType
end
class StudentEdgeType < GraphQL::Types::Relay::BaseEdge
  node_type StudentType
end
class StudentType < GraphQL::Schema::Object
  field :id, Integer
  field :age, Integer
  field :username, String
end
</source>
</blockquote><!-- Connections -->
</blockquote><!-- syntax -->

Revision as of 20:58, 5 September 2021

graphql gem for ruby.

TODO:

needs revisiting

Documentation

wiki graphql
docs https://graphql-ruby.org/guides
API docs https://graphql-ruby.org/api-doc/1.12.8/
github https://github.com/rmosolgo/graphql-ruby
homepage https://graphql-ruby.org/

Notes

graphql-ruby basics
graphql-ruby fields
graphql-ruby mutations
graphql-ruby connections

Syntax

Objects

Fields with Arguments

class User < GraphQL::Schema::Object
  field :id, Integer    # name, returntype
  field :age, Integer   # name, returntype
end

class MyGraph < GraphQL::Schema::Object
  field :user, User, do |field|
    field.argument(:id, Integer, required: true)
  end
end

Mutations

Mutations are graphql fields that trigger side effects.

  • mutations return a hash, that contains all of the fields defined on it.
  • mutations may optionally accept arguments
class MyMutation < GraphQL::Schema::RelayClassicMutation
  argument :username, String, required: true

  field :message, String, null: true    # returns string, allows null
  field :errors, [String], null, false  # returns list of strings, disallows null

  def resolve(username)
    # do thing that produces side effect
    { message: "Hello #{username}",
      errors: [] }
  end
end


class MyMutationRoot < GraphQL::Schema::RelayClassicMutation
  field :mymutation,
    mutation: MyMutation  # TODO: needs arg??
end


class MyGraph < GraphQL::Schema
  mutation(MyMutationRoot)
end