Class: SimpleSpark::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/simple_spark/client.rb', line 10

def initialize(opts = {})
  @api_key = opts[:api_key] || ENV['SPARKPOST_API_KEY']
  @api_host = opts[:api_host] || 'https://api.sparkpost.com'
  @base_path = opts[:base_path] || '/api/v1/'
  @subaccount_id = opts[:subaccount_id]
  @headers = opts[:headers]

  @logger = opts[:logger] || SimpleSpark::Client.default_logger

  fail Exceptions::InvalidConfiguration.new, 'You must provide a SparkPost API key' unless @api_key
  fail Exceptions::InvalidConfiguration.new, 'You must provide a SparkPost API host' unless @api_host # this should never occur unless the default above is changed
  fail Exceptions::InvalidConfiguration.new, 'You must provide a SparkPost base path' unless @base_path # this should never occur unless the default above is changed
  fail Exceptions::InvalidConfiguration.new, 'The headers options provided must be a valid Hash' if @headers && !@headers.is_a?(Hash)

  rails_development = true & defined?(Rails) && Rails.env.development?

  @debug = opts[:debug].nil? ? rails_development : opts[:debug]

  # switch debug params, allow for old and new parameters and supress Excon warning
  debug_options = Excon::VALID_REQUEST_KEYS.any? { |k| k == :debug } ? { debug: @debug } : { debug_request: @debug, debug_response: @debug }

  @session = Excon.new(@api_host, debug_options)
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/simple_spark/client.rb', line 8

def logger
  @logger
end

Class Method Details

.default_loggerObject



101
102
103
104
105
# File 'lib/simple_spark/client.rb', line 101

def self.default_logger
  logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
  logger.progname = 'simple_spark' if logger.respond_to?(:progname=)
  logger
end

Instance Method Details

#call(opts) ⇒ Object



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
# File 'lib/simple_spark/client.rb', line 34

def call(opts)
  method = opts[:method]
  path = opts[:path]
  body_values = opts[:body_values] || {}
  query_params = opts[:query_values] || {}
  extract_results = opts[:extract_results].nil? ? true : opts[:extract_results]

  fail Exceptions::InvalidConfiguration.new(method: method), 'Only GET, POST, PUT and DELETE are supported' unless [:get, :post, :put, :delete].include?(method)

  path = "#{@base_path}#{path}"
  params = { path: path, headers: headers }
  params[:body] = body_values.to_json unless body_values.empty?
  params[:query] = query_params unless query_params.empty?

  if @debug
    logger.debug("Calling #{method}")
    logger.debug(params)
  end

  response = @session.send(method.to_s, params)

  if @debug
    logger.debug("Response #{response.status}")
    logger.debug(response)
  end

  fail Exceptions::GatewayTimeoutExceeded, 'Received 504 from SparkPost API' if response.status == 504

  process_response(response, extract_results)

rescue Excon::Errors::Timeout
  raise Exceptions::GatewayTimeoutExceeded
end

#headersObject



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/simple_spark/client.rb', line 89

def headers
  defaults = {
    'User-Agent' => 'simple_spark/' + VERSION,
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => @api_key
  }
  defaults.merge!('X-MSYS-SUBACCOUNT' => @subaccount_id) if @subaccount_id
  defaults.merge!(@headers) if @headers
  defaults
end

#inbound_domainsObject



115
116
117
# File 'lib/simple_spark/client.rb', line 115

def inbound_domains
  Endpoints::InboundDomains.new(self)
end

#message_eventsObject



131
132
133
# File 'lib/simple_spark/client.rb', line 131

def message_events
  Endpoints::MessageEvents.new(self)
end

#metricsObject



107
108
109
# File 'lib/simple_spark/client.rb', line 107

def metrics
  Endpoints::Metrics.new(self)
end

#process_response(response, extract_results) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/simple_spark/client.rb', line 68

def process_response(response, extract_results)
  logger.warn('Response had an empty body') if (response.body.nil? || response.body == '') && response.status != 204
  return {} if response.status == 204 || response.body.nil? || response.body == ''

  response_body = JSON.parse(response.body)
  if response_body['errors']
    Exceptions::Error.fail_with_exception_for_status(response.status, response_body['errors'])
  else
    if extract_results
      response_body['results'] ? response_body['results'] : {}
    else
      response_body
    end
  end
end

#relay_webhooksObject



139
140
141
# File 'lib/simple_spark/client.rb', line 139

def relay_webhooks
  Endpoints::RelayWebhooks.new(self)
end

#sending_domainsObject



119
120
121
# File 'lib/simple_spark/client.rb', line 119

def sending_domains
  Endpoints::SendingDomains.new(self)
end

#subaccountsObject



111
112
113
# File 'lib/simple_spark/client.rb', line 111

def subaccounts
  Endpoints::Subaccounts.new(self)
end

#templatesObject



123
124
125
# File 'lib/simple_spark/client.rb', line 123

def templates
  Endpoints::Templates.new(self)
end

#transmissionsObject



127
128
129
# File 'lib/simple_spark/client.rb', line 127

def transmissions
  Endpoints::Transmissions.new(self)
end

#url_encode(s) ⇒ Object



85
86
87
# File 'lib/simple_spark/client.rb', line 85

def url_encode(s)
  s.to_s.dup.force_encoding('ASCII-8BIT').gsub(/[^a-zA-Z0-9_\-.]/) { sprintf('%%%02X', $&.unpack('C')[0]) }
end

#webhooksObject



135
136
137
# File 'lib/simple_spark/client.rb', line 135

def webhooks
  Endpoints::Webhooks.new(self)
end