Sha256: 4e359c305e81e46d9fb52f7160fb9cc740561edc1288f73690570e505f029499

Contents?: true

Size: 1.07 KB

Versions: 9

Compression:

Stored size: 1.07 KB

Contents

module JsonApiClient
  module Middleware
    class Status < Faraday::Middleware
      def call(environment)
        @app.call(environment).on_complete do |env|
          handle_status(env[:status], env)

          # look for meta[:status]
          if env[:body].is_a?(Hash)
            code = env[:body].fetch("meta", {}).fetch("status", 200).to_i
            handle_status(code, env)
          end
        end
      rescue Faraday::ConnectionFailed, Faraday::TimeoutError
        raise Errors::ConnectionError, environment
      end

      protected

      def handle_status(code, env)
        case code
        when 200..399
        when 401
          raise Errors::NotAuthorized, env
        when 403
          raise Errors::AccessDenied, env
        when 404
          raise Errors::NotFound, env[:url]
        when 409
          raise Errors::Conflict, env
        when 400..499
          # some other error
        when 500..599
          raise Errors::ServerError, env
        else
          raise Errors::UnexpectedStatus.new(code, env[:url])
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
json_api_client-1.6.1 lib/json_api_client/middleware/status.rb
json_api_client-1.6.0 lib/json_api_client/middleware/status.rb
json_api_client-1.5.3 lib/json_api_client/middleware/status.rb
json_api_client-1.5.2 lib/json_api_client/middleware/status.rb
json_api_client-1.5.1 lib/json_api_client/middleware/status.rb
json_api_client-1.5.0 lib/json_api_client/middleware/status.rb
json_api_client-1.4.0 lib/json_api_client/middleware/status.rb
json_api_client-1.3.0 lib/json_api_client/middleware/status.rb
json_api_client-1.2.0 lib/json_api_client/middleware/status.rb