Class: SerwerSMS::Http::ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/serwersms/http/api_client.rb

Direct Known Subclasses

HttpCredentials, HttpToken

Constant Summary collapse

API_URL =
'https://api2.serwersms.pl'.freeze
SYSTEM =
'client_ruby'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(api_url: API_URL, timeout: 30) ⇒ ApiClient

Returns a new instance of ApiClient.



11
12
13
14
# File 'lib/serwersms/http/api_client.rb', line 11

def initialize(api_url: API_URL, timeout: 30)
  @api_url = api_url.chomp('/')
  @timeout = timeout
end

Instance Method Details

#call(path, params = {}) ⇒ Object



16
17
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
45
46
47
48
49
50
# File 'lib/serwersms/http/api_client.rb', line 16

def call(path, params = {})
  params = params.compact
  params['system'] = SYSTEM

  apply_auth(params)

  uri = URI.parse("#{@api_url}/#{path}.json")

  Net::HTTP.start(uri.host, uri.port,
    use_ssl:      true,
    verify_mode:  OpenSSL::SSL::VERIFY_PEER,
    open_timeout: @timeout,
    read_timeout: @timeout
  ) do |http|
    request = Net::HTTP::Post.new(uri, build_headers)
    request.body = params.to_json

    response = http.request(request)

    unless response.is_a?(Net::HTTPSuccess)
      raise SerwerSMS::Error.new("HTTP #{response.code}", response.code)
    end

    result = JSON.parse(response.body)

    if result.is_a?(Hash) && result['error']
      raise SerwerSMS::Error.new(
        result.dig('error', 'message') || 'Unknown API error',
        result.dig('error', 'code')
      )
    end

    result
  end
end