Class: Graphlyte::Editors::RemoveUnneededSpreads

Inherits:
Object
  • Object
show all
Defined in:
lib/graphlyte/editors/remove_unneeded_spreads.rb

Overview

Remove unnecessary spreads.

For example in the query:

“‘ query {

User(id: 1) {
  ... on User {
    name
  }
}

} “‘

If the ‘Query.User` field has the type `User` then the spread `… on User` is tautological, and we can replace this with:

“‘ query {

User(id: 1) {
  name
}

} “‘

Instance Method Summary collapse

Constructor Details

#initialize(schema = nil) ⇒ RemoveUnneededSpreads

Returns a new instance of RemoveUnneededSpreads.



34
35
36
# File 'lib/graphlyte/editors/remove_unneeded_spreads.rb', line 34

def initialize(schema = nil)
  @schema = schema
end

Instance Method Details

#edit(doc) ⇒ Object



38
39
40
41
42
# File 'lib/graphlyte/editors/remove_unneeded_spreads.rb', line 38

def edit(doc)
  AnnotateTypes.new(@schema).edit(doc)

  inliner.edit(doc)
end

#inlinable?(fragment, parent) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/graphlyte/editors/remove_unneeded_spreads.rb', line 50

def inlinable?(fragment, parent)
  fragment.directives.none? && type_of(parent) == fragment.type_name
end

#inlinerObject



44
45
46
47
48
# File 'lib/graphlyte/editors/remove_unneeded_spreads.rb', line 44

def inliner
  @inliner ||= Editor.top_down.on_inline_fragment do |frag, action|
    action.expand(frag.selection) if inlinable?(frag, action.parent)
  end
end

#type_of(node) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/graphlyte/editors/remove_unneeded_spreads.rb', line 54

def type_of(node)
  case node
  when Syntax::Field
    node.type&.inner
  when Syntax::InlineFragment
    node.type_name
  end
end