Class: SolidusGraphqlApi::Types::Json

Inherits:
GraphQL::Types::JSON
  • Object
show all
Defined in:
lib/solidus_graphql_api/types/json.rb

Class Method Summary collapse

Class Method Details

.class_exists?(value) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
49
50
51
52
# File 'lib/solidus_graphql_api/types/json.rb', line 46

def self.class_exists?(value)
  return false if value.nil?

  Object.const_defined?(value)
rescue NameError
  false
end

.coerce_input(value, ctx) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/solidus_graphql_api/types/json.rb', line 6

def self.coerce_input(value, ctx)
  value.each do |key, field|
    case field
    when String
      value[key] = decode(field)
    when Array
      value[key] = decode_array(field, ctx)
    when Hash, ActionController::Parameters
      value[key] = coerce_input(field, ctx)
    end
  end
  value
end

.decode(value) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/solidus_graphql_api/types/json.rb', line 20

def self.decode(value)
  class_name, item_id = decode_if_relay_id(value)

  return value unless class_exists?(class_name)

  to_i_or_nil(item_id) || value
end

.decode_array(array, ctx) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/solidus_graphql_api/types/json.rb', line 28

def self.decode_array(array, ctx)
  array.map do |value|
    if value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
      coerce_input(value, ctx)
    elsif value.is_a?(String)
      decode(value)
    else
      value
    end
  end
end

.decode_if_relay_id(value) ⇒ Object



40
41
42
43
44
# File 'lib/solidus_graphql_api/types/json.rb', line 40

def self.decode_if_relay_id(value)
  GraphQL::Schema::UniqueWithinType.decode(value)
rescue ArgumentError
  [nil, nil]
end

.to_i_or_nil(value) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/solidus_graphql_api/types/json.rb', line 54

def self.to_i_or_nil(value)
  return value if value.nil?

  Integer(value)
rescue ArgumentError
  nil
end