# encoding: utf-8 # require 'json' module Mode module Sdk class Client # The Response class wraps a Mode API response # class Response attr_reader :http_response, :expected_codes # Construct a new Response instance # # @param http_response [Net::HTTPResponse] the HTTP response # @param expected_codes [optional, Array] array of expected # HTTP response codes # # @return [Mode::Sdk::Client::Response] the instance # def initialize(http_response, expected_codes = []) @http_response = http_response @expected_codes = expected_codes end # The HTTP response code # # @return [Integer] the response code # def code http_response.code.to_i end # The parsed HTTP response body # # @return [Hash] the JSON response hash # def body JSON.parse(http_response.body) end # Validate the HTTP response code # # @return [true] # def validate! raise_unexpected_code if unexpected_code? true end # Raise exception due to an unexpected response code # # @raise [Mode::Sdk::Client::AuthenticationError if the response is 401 # @raise [Mode::Sdk::Client::AuthorizationError if the response is 403 # @raise [Mode::Sdk::Client::ResponseError] for other unexpected # responses # def raise_unexpected_code case code when 401 fail Mode::Sdk::Client::AuthenticationError when 403 fail Mode::Sdk::Client::AuthorizationError else fail Mode::Sdk::Client::ResponseError, "Unexpected response: #{code}\n#{body}" end end private def unexpected_code? expected_codes.any? && !expected_codes.include?(code) end end class ResponseError < StandardError; end class AuthenticationError < StandardError; end class AuthorizationError < StandardError; end end end end