Sha256: 08eaad8f2d70311928852d63bf97f959ffe8abcdf5027fbb4e6bb6c80e858ad2

Contents?: true

Size: 933 Bytes

Versions: 4

Compression:

Stored size: 933 Bytes

Contents

module Tumbz
  module Middleware
    class Parse < Faraday::Response::Middleware
      # Parse the response body
      #
      # @param [String] body The response body
      # @return [Mixed] the parsed response
      def parse(body)
        json = MultiJson.load(body, :symbolize_keys => true)
        errors = []
        metadata = json.delete(:metadata) || []

        if json.is_a?(Hash) and json[:error].present?
          json.delete(:error)
          json.delete(:message)
          errors = [json.delete(:developerMessage)]
        end

        {
          :data => json,
          :errors => errors,
          :metadata => metadata
        }
      end

      # This method is triggered when the response has been received. It modifies
      # the value of `env[:body]`.
      #
      # @param [Hash] env The response environment
      def on_complete(env)
        env[:body] = parse(env[:body])
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tumbz-0.0.5 lib/tumbz/middleware/parse.rb
tumbz-0.0.4 lib/tumbz/middleware/parse.rb
tumbz-0.0.3 lib/tumbz/middleware/parse.rb
tumbz-0.0.2 lib/tumbz/middleware/parse.rb