Module: WCC::Contentful::Graphql::FieldHelper

Extended by:
FieldHelper
Included in:
FieldHelper
Defined in:
lib/wcc/contentful/graphql/field_helper.rb

Instance Method Summary collapse

Instance Method Details

#contentful_field(field_name, type, array: false, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/wcc/contentful/graphql/field_helper.rb', line 18

def contentful_field(field_name, type, array: false, &block)
  field_name = field_name.to_s

  type =
    case type
    when :DateTime
      types.String
    when :Coordinates
      WCC::Contentful::Graphql::Types::CoordinatesType
    when :Json
      WCC::Contentful::Graphql::Types::HashType
    else
      if type.is_a?(Symbol) || type.is_a?(String)
        types.public_send(type)
      elsif type.is_a?(GraphQL::BaseType)
        type
      else
        raise ArgumentError, "Unknown type arg '#{type}' for field #{field_name}"
      end
    end
  type = type.to_list_type if array
  field(field_name.to_sym, type) do
    resolve contentful_field_resolver(field_name)

    instance_exec(&block) if block_given?
  end
end

#contentful_field_resolver(field_name) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/wcc/contentful/graphql/field_helper.rb', line 6

def contentful_field_resolver(field_name)
  field_name = field_name.to_s

  ->(obj, _args, ctx) {
    if obj.is_a? Array
      obj.map { |o| o.dig('fields', field_name, ctx[:locale] || 'en-US') }
    else
      obj.dig('fields', field_name, ctx[:locale] || 'en-US')
    end
  }
end


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/wcc/contentful/graphql/field_helper.rb', line 46

def contentful_link_resolver(field_name, store:)
  ->(obj, _args, ctx) {
    links = obj.dig('fields', field_name, ctx[:locale] || 'en-US')
    return if links.nil?

    if links.is_a? Array
      links.reject(&:nil?).map { |l| store.find(l.dig('sys', 'id')) }
    else
      store.find(links.dig('sys', 'id'))
    end
  }
end