Class: Munson::ResponseMapper
Overview
When a JSONAPI collection (data: <Array>) is received it maps the response into multiple JSONAPI resource objects (data: <Hash>) and passes each to the #initialize_resource method so that each resource can act independently of the collection. JSONAPI collection are wrapped in a Munson::Collection which will also contain metadata from the request
Maps JSONAPI Responses to ruby objects.
ResourceMapper maps responses in 3 ways:
Instance Method Summary collapse
-
#collection ⇒ Object
Moved top level keys to the collection * errors: an array of error objects * meta: a meta object that contains non-standard meta-information.
-
#initialize(response_body) ⇒ ResponseMapper
constructor
A new instance of ResponseMapper.
- #jsonapi_resources ⇒ Object
- #resource ⇒ Object
Constructor Details
#initialize(response_body) ⇒ ResponseMapper
Returns a new instance of ResponseMapper.
55 56 57 |
# File 'lib/munson/response_mapper.rb', line 55 def initialize(response_body) @body = response_body end |
Instance Method Details
#collection ⇒ Object
Moved top level keys to the collection
-
errors: an array of error objects
-
meta: a meta object that contains non-standard meta-information.
-
jsonapi: an object describing the server’s implementation
-
links: a links object related to the primary data.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/munson/response_mapper.rb', line 64 def collection if errors? raise Exception, "IMPLEMENT ERRORS JERK" elsif collection? # Make each item in :data its own document, stick included into that document records = @body[:data].reduce([]) do |agg, resource| json = { data: resource } json[:included] = @body[:included] if @body[:included] agg << json agg end Collection.new(records.map{ |datum| Munson.factory(datum) }, meta: @body[:meta], jsonapi: @body[:jsonapi], links: @body[:links] ) else raise Munson::Error, "Called #collection, but response was a single resource. Use ResponseMapper#resource" end end |
#jsonapi_resources ⇒ Object
96 97 98 99 100 |
# File 'lib/munson/response_mapper.rb', line 96 def jsonapi_resources data = collection? ? @body[:data] : [@body[:data]] included = @body[:included] || [] (data + included) end |
#resource ⇒ Object
86 87 88 89 90 91 92 93 94 |
# File 'lib/munson/response_mapper.rb', line 86 def resource if errors? raise Exception, "IMPLEMENT ERRORS JERK" elsif resource? Munson.factory(@body) else raise Munson::Error, "Called #resource, but response was a collection of resources. Use ResponseMapper#collection" end end |