Module: Flexirest::JsonAPIProxy::Response

Extended by:
Helpers, Response
Included in:
Response
Defined in:
lib/flexirest/json_api_proxy.rb

Overview

Parsing JSON API responses

Constant Summary collapse

ID_PFIX =
'_id_'

Instance Method Summary collapse

Methods included from Helpers

singular?, type

Instance Method Details

#parse(body, object) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/flexirest/json_api_proxy.rb', line 192

def parse(body, object)
  # Save resource class for building lazy association loaders
  save_resource_class(object)

  # According to the spec:
  # "The members data and errors MUST NOT coexist in the same document."
  # Thus, if the "errors" key is present, we can return it and ignore the "data" key.
  return body['errors'] if body.include?('errors')

  # return early if data is an empty array
  return [] if body['data'] == []

  # Retrieve the resource(s) object or array from the data object
  records = body['data']

  # Convert the resource object to an array,
  # because it is easier to work with an array than a single object
  # Also keep track if record is singular or plural for the result later
  is_singular_record = records.is_a?(Hash)
  records = [records] if is_singular_record

  # Retrieve all names of linked relationships
  relationships = records.first['relationships']
  relationships = relationships ? relationships.keys : []

  included = body['included']

  # Parse the records, and retrieve all resources in a
  # (nested) array of resources that is easy to work with in Flexirest
  resources = records.map do |record|
    fetch_attributes_and_relationships(record, included, relationships)
  end

  # Pluck all attributed and associations into hashes
  resources = resources.map do |resource|
    pluck_attributes_and_relationships(resource, relationships)
  end

  # Depending on whether we got a resource object (hash) or array
  # in the beginning, return to the caller with the same type
  is_singular_record ? resources.first : resources
end

#save_resource_class(object) ⇒ Object



188
189
190
# File 'lib/flexirest/json_api_proxy.rb', line 188

def save_resource_class(object)
  @resource_class = object.is_a?(Class) ? object : object.class
end