Class: ConnectClient::Http::Async

Inherits:
Object
  • Object
show all
Defined in:
lib/connect_client/http/event_endpoint.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_url, headers) ⇒ Async

Returns a new instance of Async.



68
69
70
71
72
73
74
# File 'lib/connect_client/http/event_endpoint.rb', line 68

def initialize(base_url, headers)
  require 'em-http-request'
  require_relative 'deferred_http_response'

  @headers = headers
  @base_url = base_url.chomp('/')
end

Instance Method Details

#create_response(http_reponse, events) ⇒ Object



115
116
117
118
119
120
121
122
123
# File 'lib/connect_client/http/event_endpoint.rb', line 115

def create_response(http_reponse, events)
  status = http_reponse.response_header.status
  content_type = http_reponse.response_header['Content-Type']
  if (http_reponse.error.to_s.empty?)
    ConnectClient::EventPushResponse.new status, content_type, http_reponse.response, events
  else
    ConnectClient::EventPushResponse.new status, content_type, http_reponse.error, events
  end
end

#send(path, body, events) ⇒ Object

Raises:



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/connect_client/http/event_endpoint.rb', line 76

def send(path, body, events)
  raise AsyncHttpError unless defined?(EventMachine) && EventMachine.reactor_running?

  use_syncrony = defined?(EM::Synchrony)

  if use_syncrony
    send_using_synchrony(path, body, events)
  else
    send_using_deferred(path, body, events)
  end
end

#send_using_deferred(path, body, events) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/connect_client/http/event_endpoint.rb', line 88

def send_using_deferred(path, body, events)
  deferred = DeferredHttpResponse.new
  url_string = "#{@base_url}#{path}".chomp('/')
  http = EventMachine::HttpRequest.new(url_string).post(:body => body, :head => @headers)
  http_callback = Proc.new do
    begin
      response = create_response http, events
      deferred.succeed response
    rescue => error
      deferred.fail error
    end
  end

  http.callback &http_callback
  http.errback &http_callback

  deferred
end

#send_using_synchrony(path, body, events) ⇒ Object



107
108
109
110
111
112
113
# File 'lib/connect_client/http/event_endpoint.rb', line 107

def send_using_synchrony(path, body, events)
  url_string = "#{@base_url}#{path}".chomp('/')
  http = EventMachine::HttpRequest.new(url_string).
          post(:body => body, :head => @headers)

  create_response http, events
end