Sha256: a8e9ca85f9f4b40276440b9ce285b30a65f003f016a604970c9841daac8e7886

Contents?: true

Size: 978 Bytes

Versions: 13

Compression:

Stored size: 978 Bytes

Contents

# frozen_string_literal: true
module Prop

  # Convenience middleware that conveys the message configured on a Prop handle as well
  # as time left before the current window has passed in a Retry-After header.
  class Middleware

    # Default error handler
    class DefaultErrorHandler
      def self.call(env, error)
        body    = error.description || "This action has been rate limited"
        headers = { "Content-Type" => "text/plain", "Content-Length" => "#{body.size}", "Retry-After" => "#{error.retry_after}" }

        [ 429, headers, [ body ]]
      end
    end

    def initialize(app, options = {})
      @app     = app
      @options = options
      @handler = options[:error_handler] || DefaultErrorHandler
    end

    def call(env)
      begin
        @app.call(env)
      rescue Prop::RateLimited => e
        render_response(env, e)
      end
    end

    protected

    def render_response(env, error)
      @handler.call(env, error)
    end
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
prop-2.9.0 lib/prop/middleware.rb
prop-2.8.0 lib/prop/middleware.rb
prop-2.7.0 lib/prop/middleware.rb
prop-2.6.1 lib/prop/middleware.rb
prop-2.6.0 lib/prop/middleware.rb
prop-2.5.0 lib/prop/middleware.rb
prop-2.4.0 lib/prop/middleware.rb
prop-2.3.0 lib/prop/middleware.rb
prop-2.2.5 lib/prop/middleware.rb
prop-2.2.4 lib/prop/middleware.rb
prop-2.2.2 lib/prop/middleware.rb
prop-2.2.1 lib/prop/middleware.rb
prop-2.2.0 lib/prop/middleware.rb