class GraphQL::Rails::Operations
Base type for operations classes in the Rails
app. Operations
are specified in a manner similar to controller actions, and can access variables and state localized to the current operation. Classes can define callbacks similar to controller 'filters'.
Public Class Methods
mutation(hash, &block)
click to toggle source
Define a mutation operation. Definitions should have the following form:
mutation :feed_cat => {appetite: Integer, last_meal: DateTime} do description 'This mutation feeds the cat and returns its appetite' argument :cat_id, Integer, :required argument :mouse_id, Integer, :required resolve do cat = Cat.find(args[:cat_id]) mouse = Mouse.find(args[:mouse_id]) raise 'Cannot find cat or mouse' if cat.nil? || mouse.nil? cat.feed(mouse) {appetite: cat.appetite, last_meal: DateTime.now} end end
# File lib/graphql/rails/operations.rb, line 63 def self.mutation(hash, &block) hash = extract_pair(hash) unless hash[:type].is_a?(Hash) raise 'Mutation must be specified with a Hash result type' end Rails.logger.debug "Adding mutation: #{Types.to_field_name(hash[:name])}" definition = MutationDefinition.new(self) definition.run(&block) definition.run do name hash[:name] type hash[:type] end Schema.add_mutation definition.field end
new(options = {})
click to toggle source
Initialize an instance with state pertaining to the current operation. Accessors for this state are created and proxied through to the specified options hash.
# File lib/graphql/rails/operations.rb, line 14 def initialize(options = {}) @options = OpenStruct.new(options) self.class.instance_eval do def_delegators :@options, *options.keys end end
query(hash, &block)
click to toggle source
Define a query operation. Definitions should have the following form:
query :find_cats => [AnimalInterface] do description 'This query returns a list of Cat models' argument :age, Integer, :required argument :breed, String uses CatType resolve do raise 'Too old' if args[:age] > 20 Cat.find(age: args[:age], breed: args[:breed]) end end
# File lib/graphql/rails/operations.rb, line 34 def self.query(hash, &block) hash = extract_pair(hash) Rails.logger.debug "Adding query: #{Types.to_field_name(hash[:name])}" definition = QueryDefinition.new(self) definition.run(&block) definition.run do name hash[:name] type hash[:type] end Schema.add_query definition.field end
Private Class Methods
extract_pair(hash)
click to toggle source
Extract parts from a hash passed to the operation definition DSL
.
# File lib/graphql/rails/operations.rb, line 242 def self.extract_pair(hash) unless hash.length == 1 raise 'Hash must contain a single :name => Type pair' end {name: hash.keys.first, type: hash.values.first} end