class HerdstServicecall::Middleware

Public Class Methods

new(app) click to toggle source
# File lib/herdst_servicecall/middleware.rb, line 5
def initialize(app)
    @app = app
    @event_path = HerdstServicecall.config.event_path
    @healthcheck_path = "/healthcheck"
end

Public Instance Methods

call(env) click to toggle source
# File lib/herdst_servicecall/middleware.rb, line 12
def call(env)
    if env["REQUEST_PATH"] == @healthcheck_path
        return [
            200,
            { "Content-Type" => "text/html" },
            [ "" ]
        ]
    end
    
    if env["REQUEST_METHOD"] == "POST"
        req = nil
        
        unless env["REQUEST_PATH"]
            req = Rack::Request.new(env)
            
            env["REQUEST_PATH"] = req.path
        end
        
        if env["REQUEST_PATH"] == @event_path
            req = Rack::Request.new(env) unless req
            body = req.body.read
            token = Rack::Utils.parse_nested_query(req.query_string)["token"] rescue nil
            
            if body
                response = HerdstServicecall.receive(token, body)
                
                return [
                    response.code,
                    { "Content-Type" => "application/json" },
                    [ response.to_json ]
                ]
            end
        end
    end
    
    return @app.call(env)
end