Sha256: f0c40085434129e4ab96e5a63a3ee29bf5e07547e8bfdc172c89d64ad8186961

Contents?: true

Size: 934 Bytes

Versions: 1

Compression:

Stored size: 934 Bytes

Contents

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, e)
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prop-0.7.4 lib/prop/middleware.rb