Class: CaliperApi::Poster

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/caliper_api/http.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePoster

Returns a new instance of Poster.



10
11
12
# File 'lib/caliper_api/http.rb', line 10

def initialize
  @base_uri = Caliper.config[:api_host]
end

Class Method Details

.send(url, data) ⇒ Object



14
15
16
# File 'lib/caliper_api/http.rb', line 14

def self.send(url, data)
  instance.post(url, data)
end

Instance Method Details

#post(url, data = "") ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/caliper_api/http.rb', line 18

def post(url, data = "")
  begin
    uri = URI.parse(@base_uri + url)
    http = Net::HTTP.new(uri.host, uri.port)

    http.open_timeout = 5 # in seconds
    http.read_timeout = 5 # in seconds

    request = Net::HTTP::Post.new(uri.request_uri)
    request["X_API_KEY"] = Caliper.config[:api_key]
    request["Content-Type"] = "application/json"
    request["Accept"] = "application/json"

    request.body = data

    response = http.request(request)

    status = response.code.to_i
    if status == 401
      Caliper.logger.error "CaliperApi: Error: Not authorized check your API key on #{Caliper.config[:api_host]}"
    elsif status > 400
      Caliper.logger.error "CaliperApi: Error: got #{response.code} from server"
    end
  rescue Exception => e
    Caliper.logger.error "CaliperApi: Http error: #{e.message}"
  end
end