Class: Snov::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/snov/client.rb

Defined Under Namespace

Classes: AuthError, BadGatewayError, BadRequest, ForbiddenError, GatewayTimeOut, MethodNotAllowed, OutOfCreditsError, ResponseError, SnovError, TimedOut, UnauthorizedError

Constant Summary collapse

ERROR_CLASSES =
{ 401 => UnauthorizedError, 502 => BadGatewayError, 403 => ForbiddenError,
504 => GatewayTimeOut, 400 => BadRequest, 405 => MethodNotAllowed }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, client_secret:, access_token: nil, timeout_seconds: 90) ⇒ Client

Returns a new instance of Client.



46
47
48
49
50
51
# File 'lib/snov/client.rb', line 46

def initialize(client_id:, client_secret:, access_token: nil, timeout_seconds: 90)
  self.client_id = client_id.to_str
  self.client_secret = client_secret.to_str
  @access_token = access_token
  @timeout_seconds = timeout_seconds.to_int
end

Class Method Details

.select_error_class(resp, fallback: ResponseError) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/snov/client.rb', line 38

def self.select_error_class(resp, fallback: ResponseError)
  if resp&.body.to_s.include?('you ran out of credits')
    OutOfCreditsError
  else
    ERROR_CLASSES.fetch(resp.status, fallback)
  end
end

Instance Method Details

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



53
54
55
56
57
58
59
60
61
62
# File 'lib/snov/client.rb', line 53

def get(path, params = {})
  resp = conn.get(path) do |req|
    req.body = MultiJson.dump(params.merge('access_token' => access_token))
    req.options.timeout = timeout_seconds # open/read timeout in seconds
    req.options.open_timeout = timeout_seconds # connection open timeout in seconds
  end
  parse_response(resp, path, params)
rescue Faraday::TimeoutError, Timeout::Error => e
  raise TimedOut, e.message
end

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



64
65
66
67
68
69
70
71
72
73
# File 'lib/snov/client.rb', line 64

def post(path, params = {})
  resp = conn.post(path) do |req|
    req.body = MultiJson.dump(params.merge('access_token' => access_token))
    req.options.timeout = timeout_seconds # open/read timeout in seconds
    req.options.open_timeout = timeout_seconds # connection open timeout in seconds
  end
  parse_response(resp, path, params)
rescue Faraday::TimeoutError, Timeout::Error => e
  raise TimedOut, e.message
end