Class: Her::Middleware::MnoeApiV1ParseJson

Inherits:
ParseJSON
  • Object
show all
Defined in:
lib/her_extension/middleware/mnoe_api_v1_parse_json.rb

Overview

This middleware expects the resource/collection data to be contained in the ‘data` key of the JSON object

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object

This method is triggered when the response has been received. It modifies the value of ‘env`.

Parameters:

  • env (Hash)

    The response environment



44
45
46
47
48
49
50
51
# File 'lib/her_extension/middleware/mnoe_api_v1_parse_json.rb', line 44

def on_complete(env)
  env[:body] = case env[:status]
  when 204
    parse('{}')
  else
    parse(env[:body])
  end
end

#parse(body) ⇒ Mixed

Parse the response body

Parameters:

  • body (String)

    The response body

Returns:

  • (Mixed)

    the parsed response



11
12
13
14
15
16
17
18
# File 'lib/her_extension/middleware/mnoe_api_v1_parse_json.rb', line 11

def parse(body)
  json = parse_json(body)
  parse_types({
    :data => json[:data] || {},
    :errors => json[:errors] || {},
    :metadata => json[:metadata] || {}
  })
end

#parse_types(res) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/her_extension/middleware/mnoe_api_v1_parse_json.rb', line 20

def parse_types(res)
  case
  when res.kind_of?(Array)
    return res.map { |e| parse_types(e) }
  when res.kind_of?(Hash) && res[:cents] && res[:currency]
    Money.new(res[:cents],res[:currency])
  when res.kind_of?(Hash)
    hash = res.dup
    hash.each do |k,v|
      hash[k] = parse_types(v)
    end
    return hash
  when res.is_a?(String) && res =~ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/i
    return Time.iso8601(res)
  else
    return res
  end
end