Class: GraphQL::EnumType

Inherits:
BaseType show all
Defined in:
lib/graphql/enum_type.rb

Overview

Represents a collection of related values. By convention, enum names are SCREAMING_CASE_NAMES, but other identifiers are supported too.

You can use as return types or as inputs.

By default, enums are passed to resolve functions as the strings that identify them, but you can provide a custom Ruby value with the value: keyword.

Examples:

An enum of programming languages

LanguageEnum = GraphQL::EnumType.define do
  name "Languages"
  description "Programming languages for Web projects"
  value("PYTHON", "A dynamic, function-oriented language")
  value("RUBY", "A very dynamic language aimed at programmer happiness")
  value("JAVASCRIPT", "Accidental lingua franca of the web")
end

Using an enum as a return type

field :favoriteLanguage, LanguageEnum, "This person's favorite coding language"
# ...
# In a query:
Schema.execute("{ coder(id: 1) { favoriteLanguage } }")
# { "data" => { "coder" => { "favoriteLanguage" => "RUBY" } } }

Defining an enum input

field :coders, types[CoderType] do
  argument :knowing, types[LanguageType]
  resolve ->(obj, args, ctx) {
    Coder.where(language: args[:knowing])
  }
end

Using an enum as input

{
  # find coders who know Python and Ruby
  coders(knowing: [PYTHON, RUBY]) {
    name
    hourlyRate
  }
}

Enum whose values are different in Ruby-land

GraphQL::EnumType.define do
  # ...
  # use the `value:` keyword:
  value("RUBY", "Lisp? Smalltalk?", value: :rb)
end

# Now, resolve functions will receive `:rb` instead of `"RUBY"`
field :favoriteLanguage, LanguageEnum
resolve ->(obj, args, ctx) {
  args[:favoriteLanguage] # => :rb
}

Enum whose values are different in ActiveRecord-land

class Language < ActiveRecord::BaseType
  enum language: {
    rb: 0
  }
end

# Now enum type should be defined as
GraphQL::EnumType.define do
  # ...
  # use the `value:` keyword:
  value("RUBY", "Lisp? Smalltalk?", value: 'rb')
end

Defined Under Namespace

Classes: EnumValue, UnresolvedValueError

Instance Attribute Summary

Attributes inherited from BaseType

#description, #name

Instance Method Summary collapse

Methods inherited from BaseType

#==, #coerce_input, #connection_type, #define_connection, #define_edge, #edge_type, #get_field, resolve_related_type, #resolve_type, #to_list_type, #to_non_null_type, #unwrap, #valid_input?, #validate_input

Methods included from Define::InstanceDefinable

#define, #metadata, #redefine

Methods included from Define::NonNullWithBang

#!

Constructor Details

#initializeEnumType

Returns a new instance of EnumType


77
78
79
# File 'lib/graphql/enum_type.rb', line 77

def initialize
  @values_by_name = {}
end

Instance Method Details

#add_value(enum_value) ⇒ Object

Parameters:

  • enum_value (EnumValue)

    A value to add to this type’s set of values


88
89
90
# File 'lib/graphql/enum_type.rb', line 88

def add_value(enum_value)
  @values_by_name[enum_value.name] = enum_value
end

#coerce_non_null_input(value_name) ⇒ Object

Get the underlying value for this enum value

Examples:

get episode value from Enum

episode = EpisodeEnum.coerce("NEWHOPE")
episode # => 6

Parameters:

  • value_name (String)

    the string representation of this enum value

Returns:

  • (Object)

    the underlying value for this enum value


121
122
123
124
125
126
127
# File 'lib/graphql/enum_type.rb', line 121

def coerce_non_null_input(value_name)
  if @values_by_name.key?(value_name)
    @values_by_name.fetch(value_name).value
  else
    nil
  end
end

#coerce_result(value, warden = nil) ⇒ Object


129
130
131
132
133
134
135
136
137
# File 'lib/graphql/enum_type.rb', line 129

def coerce_result(value, warden = nil)
  all_values = warden ? warden.enum_values(self) : @values_by_name.each_value
  enum_value = all_values.find { |val| val.value == value }
  if enum_value
    enum_value.name
  else
    raise(UnresolvedValueError, "Can't resolve enum #{name} for #{value}")
  end
end

#kindObject


97
98
99
# File 'lib/graphql/enum_type.rb', line 97

def kind
  GraphQL::TypeKinds::ENUM
end

#to_sObject


139
140
141
# File 'lib/graphql/enum_type.rb', line 139

def to_s
  name
end

#validate_non_null_input(value_name, warden) ⇒ Object


101
102
103
104
105
106
107
108
109
110
111
# File 'lib/graphql/enum_type.rb', line 101

def validate_non_null_input(value_name, warden)
  result = GraphQL::Query::InputValidationResult.new
  allowed_values = warden.enum_values(self)
  matching_value = allowed_values.find { |v| v.name == value_name }

  if matching_value.nil?
    result.add_problem("Expected #{JSON.generate(value_name, quirks_mode: true)} to be one of: #{allowed_values.map(&:name).join(', ')}")
  end

  result
end

#valuesHash<String => EnumValue>

Returns {name => value} pairs contained in this type

Returns:

  • (Hash<String => EnumValue>)

    {name => value} pairs contained in this type


93
94
95
# File 'lib/graphql/enum_type.rb', line 93

def values
  @values_by_name
end

#values=(new_values) ⇒ Object

Parameters:

  • new_values (Array<EnumValue>)

    The set of values contained in this type


82
83
84
85
# File 'lib/graphql/enum_type.rb', line 82

def values=(new_values)
  @values_by_name = {}
  new_values.each { |enum_value| add_value(enum_value) }
end