Class: TrackingMore::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/trackingmore/request.rb

Constant Summary collapse

@@apiBaseUrl =
'api.trackingmore.com'
@@apiPort =
443
@@apiVersion =
'v4'
@@timeout =
10

Class Method Summary collapse

Class Method Details

.get_request_header(apiKey) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/trackingmore/request.rb', line 18

def self.get_request_header(apiKey)
  headers = {}
  headers['Accept'] = 'application/json'
  headers['Content-Type'] = 'application/json'
  headers['Tracking-Api-Key'] = apiKey
  return headers
end

.get_request_url(path) ⇒ Object



12
13
14
15
16
# File 'lib/trackingmore/request.rb', line 12

def self.get_request_url(path)
  pact = @@apiPort == 443 ? 'https' : 'http'
  url = pact+'://'+@@apiBaseUrl+'/'+@@apiVersion+'/'+path
  return url
end

.make_request(method = 'GET', path = '', params = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/trackingmore/request.rb', line 26

def self.make_request(method = 'GET', path = '', params = nil)

  if TrackingMore.api_key.to_s.empty?
    raise TrackingMore::TrackingMoreException.new(TrackingMore::Consts::ErrEmptyAPIKey)
  end

  url = get_request_url(path)

  headers = get_request_header(TrackingMore.api_key)


  uri = URI.parse(url)

  if method.downcase == 'get' && params!=nil
    query_string = URI.encode_www_form(params)
    uri.query = query_string
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'

  http.open_timeout = 10

  http.read_timeout = 10

  request_class = case method.downcase
                  when 'get' then Net::HTTP::Get
                  when 'post' then Net::HTTP::Post
                  when 'put' then Net::HTTP::Put
                  when 'delete' then Net::HTTP::Delete
                  else raise ArgumentError, "Invalid HTTP method: #{method}"
                  end

  request = request_class.new(uri.request_uri)

  headers.each { |key, value| request[key] = value }

  if  params!=nil && (method.downcase == 'post' || method.downcase == 'put')
    request.body = params.to_json
  end

  begin
    response = http.request(request)
    begin
      parsed_response = JSON.parse(response.body)
      parsed_response
    rescue JSON::ParserError
      response.body
    end
  rescue StandardError => e
    { 'error' => e.message }
  end
end