Class: GraphQL::Connection

Inherits:
Node
  • Object
show all
Defined in:
lib/graphql/connection.rb

Overview

Connections wrap collections of objects.

Out of the box, the only field it has is ‘edges`, which provides access to the members of the collection.

You can define a custom Connection to use. This allows you to define fields and calls at the collection level (rather than the item level)

You can access the collection as ‘target` (Node#target).

Examples:

class UpvotesConnection < GraphQL::Collection
  type :upvotes # adds it to the schema
  call :first, -> (prev_items, first) { prev_items.first(first.to_i) }
  call :after, -> (prev_items, after) { prev_items.select {|i| i.id > after.to_i } }

  field.number(:count) # delegates to the underlying collection
  field.boolean(:any)

  def any
    target.any?
  end
end

# Then, this connection will be used for connections whose names match:
class PostNode < GraphQL::Node
  field.upvotes(:upvotes)
  # ^^ uses `UpvotesConnection` based on naming convention
end

# And you can use the fields in a query:
<<QUERY
find_post(10) {
  title,
  upvotes {
    count,
    any,
    edges {
      node { created_at }
    }
  }
}
QUERY

Direct Known Subclasses

Introspection::Connection

Instance Attribute Summary

Attributes inherited from Node

#original_target, #query, #syntax_fields, #target

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#__type__, all_fields, #apply_calls, #as_result, call, calls, #context, cursor, desc, description, exposes, exposes_class_names, field, #finished_value, #initialize, #method_missing, own_calls, own_fields, remove_field, respond_to_field?, schema_name, type

Constructor Details

This class inherits a constructor from GraphQL::Node

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class GraphQL::Node

Class Method Details

.default_schema_nameObject



61
62
63
# File 'lib/graphql/connection.rb', line 61

def default_schema_name
  name.split("::").last.sub(/Connection$/, '').underscore
end

Instance Method Details

#edge_fieldsObject



46
47
48
# File 'lib/graphql/connection.rb', line 46

def edge_fields
  @edge_fields ||= syntax_fields.find { |f| f.identifier == "edges" }.fields
end

#edgesObject



50
51
52
53
54
55
56
57
58
# File 'lib/graphql/connection.rb', line 50

def edges
  raise "#{self.class} expected a connection, but got `nil`" if target.nil?
  target.map do |item|
    node_class = GraphQL::SCHEMA.type_for_object(item)
    node = node_class.new(item, fields: edge_fields, query: query)
    res = node.as_result
    res
  end
end