Class: Opera::MobileStoreSDK::FaradayMiddleware::ResponseParser

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/opera/mobile_store_sdk/faraday_middleware/response_parser.rb

Overview

Parses the responses to models:

Instance Method Summary collapse

Instance Method Details

#call(request_env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/opera/mobile_store_sdk/faraday_middleware/response_parser.rb', line 10

def call(request_env)
  # do something with the request
  # request_env[:request_headers].merge!(...)

  @app.call(request_env).on_complete do |response_env|

    benchmark = Benchmark.measure "api_response_parsing" do
      # Parse to XML:
      xml_data = Nokogiri::XML(response_env[:body])

      response_env[:found_rows] = xml_data.xpath("string(/xml/*/@found_rows)").to_i
      response_env[:timestamp] = xml_data.xpath("string(/xml/*/@timestamp)").to_i

      real_root_name = xml_data.xpath("name(/xml/*)")

      parser_class = case real_root_name
      when "platforms"
        Opera::MobileStore::DevicePlatform
      when "platform_families"
        Opera::MobileStore::DevicePlatformFamily
      else
        "Opera::MobileStore::#{real_root_name.classify}".safe_constantize
      end

      # Parse each node:
      collection_path = "/xml/#{real_root_name}"
      collection_path += case real_root_name
      when "compatibility"
        # Add the product id to the compatibility child nodes if
        # a product compatibility was queried instead of a build compat:
        product_param = request_env.url.query[/product_id=(\d+)/i]
        if product_param.present?
          product_id = product_param.split('=').last.to_i
          xml_data.xpath("#{collection_path}/product").each do |product_compat_node|
            product_compat_node.set_attribute('id', product_id)
          end
        end

        # Return an empty string...
        ""
      else
        "/#{real_root_name.singularize}"
      end

      parsed_data = xml_data.xpath(collection_path).map do |item_node|
        parser_class.build_from_nokogiri_node item_node
      end

      # replace body with parsed_data:
      response_env[:body] = parsed_data
    end

    response_env[:opera_api_response_parsing_tms] = benchmark
  end
end