Module: JSONAPIonify::Api::Resource::Includer

Extended by:
ActiveSupport::Concern
Included in:
JSONAPIonify::Api::Resource
Defined in:
lib/jsonapionify/api/resource/includer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.includes_to_hashes(path) ⇒ Object



79
80
81
82
83
84
# File 'lib/jsonapionify/api/resource/includer.rb', line 79

def self.includes_to_hashes(path)
  path.to_s.split(',').each_with_object({}) do |path, obj|
    rel, *sub_path = path.split('.')
    obj[rel]       = includes_to_hashes(sub_path.join('.'))
  end
end

Instance Method Details

#append_included(context, included) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/jsonapionify/api/resource/includer.rb', line 47

def append_included(context, included)
  if included.present?
    context.response_object[:included] = included
    context.response_object[:included].tap(&:uniq!).reject! do |r|
      Array.wrap(context.response_object[:included]).include?(r) ||
        Array.wrap(context.response_object[:data]).include?(r)
    end
  end
end

#expand_body(body) ⇒ Object



86
87
88
89
90
91
92
93
94
95
# File 'lib/jsonapionify/api/resource/includer.rb', line 86

def expand_body(body)
  case body
  when Rack::BodyProxy
    json = JSONAPIonify.parse(body.body.join)
    Array.wrap(json[:data]) + (json[:included] || [])
  when Array
    json = JSONAPIonify.parse(body.join)
    Array.wrap(json[:data]) + (json[:included] || [])
  end
end

#fetch_included(context, **overrides) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/jsonapionify/api/resource/includer.rb', line 57

def fetch_included(context, **overrides)
  collection = JSONAPIonify::Structure::Collections::IncludedResources.new
  context.includes.each_with_object(collection) do |(name, _),|
    res = self.class.relationship(name)
    if res.rel.includable?
      overrides = overrides.merge includes:      context.includes[name],
                                  errors:        context.errors,
                                  root_request?: false
      *, body   =
        case res.rel
        when Relationship::One
          res.call_action(:read, context.request, **overrides)
        when Relationship::Many
          res.call_action(:list, context.request, **overrides)
        end
      collection.concat expand_body(body)
    else
      error :relationship_not_includable, res.rel.name
    end
  end.uniq
end