Sha256: 6f3157145e4aae71d8360f12d52210fd10492c71415983886eec25ae5fea08bc

Contents?: true

Size: 1.13 KB

Versions: 7

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

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

          if env[:body].is_a?(Hash)
            status = env[:body].fetch('meta', {}).fetch('status', 200).to_i
            handle_status(status, env)
          end
        end
      rescue Faraday::ConnectionFailed, Faraday::TimeoutError => e
        raise ConnectionError, e
      end

      private

      def handle_status(status, environment)
        return if (200..399).cover?(status)

        case status
        when 401 then raise NotAuthorized.new(status, environment)
        when 403 then raise AccessDenied.new(status, environment)
        when 404 then raise ResourceNotFound.new(status, environment)
        when 409 then raise ResourceConflict.new(status, environment)
        when 422 then raise UnprocessableEntity.new(status, environment)
        when 500..599 then raise ServerError.new(status, environment)
        else raise UnexpectedStatus.new(status, environment)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
bima-shark-sdk-3.1.1 lib/shark/middleware/status.rb
bima-shark-sdk-2.5.0 lib/shark/middleware/status.rb
bima-shark-sdk-3.1.0 lib/shark/middleware/status.rb
bima-shark-sdk-3.0.0 lib/shark/middleware/status.rb
bima-shark-sdk-2.4.4 lib/shark/middleware/status.rb
bima-shark-sdk-2.4.3 lib/shark/middleware/status.rb
bima-shark-sdk-2.4.2 lib/shark/middleware/status.rb