Class: ZaloAPI::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|config| ... } ⇒ Client

Returns a new instance of Client.

Yields:

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
# File 'lib/zalo_api/client.rb', line 17

def initialize
  raise ArgumentError, 'block not given' unless block_given?

  @config = ZaloAPI::Configuration.new
  yield config

  config.retry = !!config.retry # nil -> false
  set_default_logger
end

Instance Attribute Details

#configConfiguration (readonly)

Returns Config instance.

Returns:



15
16
17
# File 'lib/zalo_api/client.rb', line 15

def config
  @config
end

Instance Method Details

#build_connectionObject

Called by #connection to build a connection. Can be overwritten in a subclass to add additional middleware and make other configuration changes.

Uses middleware according to configuration options.

Request logger if logger is not nil

Retry middleware if retry is true



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/zalo_api/client.rb', line 44

def build_connection
  Faraday.new(config.options) do |builder|
    # response
    builder.use ZaloAPI::Middleware::Response::ParseJson
    builder.use ZaloAPI::Middleware::Response::SanitizeResponse
    builder.use ZaloAPI::Middleware::Response::Logger, config.logger if config.logger

    # request
    builder.use ZaloAPI::Middleware::Request::UrlBasedAccessToken, config.access_token
    builder.use ZaloAPI::Middleware::Request::EncodeJson
    builder.use ZendeskAPI::Middleware::Request::Retry, :logger => config.logger if config.retry

    builder.adapter(Faraday.default_adapter)
  end
end

#connectionFaraday::Connection

Creates a connection if there is none, otherwise returns the existing connection.

Returns:

  • (Faraday::Connection)

    Faraday connection for the client



30
31
32
33
# File 'lib/zalo_api/client.rb', line 30

def connection
  @connection ||= build_connection
  return @connection
end

#set_default_loggerObject



60
61
62
63
64
65
66
# File 'lib/zalo_api/client.rb', line 60

def set_default_logger
  if config.logger.nil? || config.logger == true
    require 'logger'
    config.logger = Logger.new($stderr)
    config.logger.level = Logger::WARN
  end
end