Sha256: 482e0e8c044121114cd4dc39374a03188e19a0623e8525e0ba31ed70c59a69ac

Contents?: true

Size: 1.13 KB

Versions: 4

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
        raise ConnectionError, environment
      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

4 entries across 4 versions & 1 rubygems

Version Path
bima-shark-sdk-2.4.1 lib/shark/middleware/status.rb
bima-shark-sdk-2.4.0 lib/shark/middleware/status.rb
bima-shark-sdk-2.3.1 lib/shark/middleware/status.rb
bima-shark-sdk-2.3.0 lib/shark/middleware/status.rb