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



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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/flexirest/json_api_proxy.rb', line 208

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

#resource_classObject



204
205
206
# File 'lib/flexirest/json_api_proxy.rb', line 204

def resource_class
  Thread.current[:flexirest_jsonapi_resource_class]
end

#save_resource_class(object) ⇒ Object

extend self makes Response a single shared object too. The resource class saved here is read again while building lazy association loaders during the same parse, so it must be per-thread: otherwise a concurrent parse of a different model would corrupt association resolution.



200
201
202
# File 'lib/flexirest/json_api_proxy.rb', line 200

def save_resource_class(object)
  Thread.current[:flexirest_jsonapi_resource_class] = object.is_a?(Class) ? object : object.class
end