class CatchBox::Middleware

Public Class Methods

new(app, fanout:, endpoint:) click to toggle source
# File lib/catch_box/middleware.rb, line 8
def initialize(app, fanout:, endpoint:)
  @app = app
  @fanout = fanout
  @endpoint = endpoint
end

Public Instance Methods

call(env) click to toggle source
# File lib/catch_box/middleware.rb, line 14
def call(env)
  dup.call!(env)
end

Protected Instance Methods

call!(env) click to toggle source
# File lib/catch_box/middleware.rb, line 20
def call!(env)
  request = ::Rack::Request.new(env)

  return @app.call(env) unless request.post?
  return @app.call(env) unless request.path == @endpoint

  body = (
    request.body.rewind
    request.body.read
  )

  payload = ::Rack::Utils.parse_query(body) if request.content_type == "application/x-www-form-urlencoded"
  payload = ::JSON.parse(body) if %r{application/json}i.match?(request.content_type)

  @fanout.emit(payload, request.env)

  [
    200,
    {},
    []
  ]
rescue ::CatchBox::NotAuthorized
  [
    400,
    {},
    []
  ]
end