class HerdstServicecall::Receiver

Attributes

config[RW]
events[RW]

Public Class Methods

new(config) click to toggle source
# File lib/herdst_servicecall/receiver.rb, line 8
def initialize(config)
    self.config = config
end

Public Instance Methods

receive(token, data) click to toggle source
# File lib/herdst_servicecall/receiver.rb, line 13
def receive(token, data)
    request = Request.new(nil, nil)
    
    begin
        verify_token!(token)
        
        request.parse!(data)
        
        action = self.config.events[request.event.to_sym] rescue nil
        
        raise ResponderError.new(request.event, "Invalid event") unless action
        
        action_class_name, action_name = action.split("#")
        action_class = "#{action_class_name.classify}ServiceEvent".constantize.new(request.event, request.body)
        response = action_class.send(action_name, request.body)
        
        Response.new(request.event, 200, response)
    rescue Exception => ex
        if ex.instance_of?(ResponderError)
            ex.response
            
        elsif ex.instance_of?(JWT::VerificationError)
            Response.new(request.event, 400, {
                :error => ex.message
            })
            
        elsif ex.instance_of?(JWT::DecodeError)
            Response.new(request.event, 400, {
                :error => "Invalid token"
            })
            
        else
            Response.new(request.event, 400, {
                :error => ex.message
            })
            
        end
    end
end

Private Instance Methods

verify_token!(token) click to toggle source
# File lib/herdst_servicecall/receiver.rb, line 55
def verify_token!(token)
    JWT.decode(
        token, 
        self.config.jwt_secret, 
        true,
        { algorithm: self.config.jwt_algorithm }
    )
end