Skip to content

Commit c5d44d9

Browse files
committed
switch to faraday http request agent
1 parent d8626c4 commit c5d44d9

18 files changed

+133
-143
lines changed

lib/mailjet/connection.rb

+33-45
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,32 @@
1-
require 'rest_client'
1+
require 'faraday'
22
require 'yajl'
33

44
module Mailjet
55
class Connection
66

7-
attr_accessor :adapter, :public_operations, :read_only, :perform_api_call, :read_timeout, :open_timeout
7+
attr_accessor :adapter, :public_operations, :read_only, :perform_api_call, :api_key, :secret_key, :options
88
alias :read_only? :read_only
99

1010
def [](suburl, &new_block)
11-
broken_url = url.split("/")
11+
broken_url = uri.path.split("/")
1212
if broken_url.include?("contactslist") && broken_url.include?("managemanycontacts") && broken_url.last.to_i > 0
13-
self.class.new(url, options[:user], options[:password], options)
13+
self.class.new(uri, api_key, secret_key, options)
1414
else
15-
self.class.new(concat_urls(url, suburl), options[:user], options[:password], options)
15+
self.class.new(concat_urls(suburl), api_key, secret_key, options)
1616
end
1717
end
1818

1919
def initialize(end_point, api_key, secret_key, options = {})
20-
# #charles proxy
21-
# RestClient.proxy = "http://127.0.0.1:8888"
22-
# #
23-
# #Output for debugging
24-
# RestClient.log =
25-
# Object.new.tap do |proxy|
26-
# def proxy.<<(message)
27-
# Rails.logger.info message
28-
# end
29-
# end
30-
# #
31-
adapter_class = options[:adapter_class] || RestClient::Resource
20+
self.options = options
21+
self.api_key = api_key
22+
self.secret_key = secret_key
3223
self.public_operations = options[:public_operations] || []
3324
self.read_only = options[:read_only]
34-
self.read_timeout = options[:read_timeout]
35-
self.open_timeout = options[:open_timeout]
36-
# self.adapter = adapter_class.new(end_point, options.merge(user: api_key, password: secret_key, :verify_ssl => false, content_type: 'application/json'))
37-
self.adapter = adapter_class.new(end_point, options.merge(user: api_key, password: secret_key, content_type: 'application/json', read_timeout: self.read_timeout, open_timeout: self.open_timeout))
25+
self.adapter = Faraday.new(end_point, ssl: { verify: false }) do |conn|
26+
conn.response :raise_error, include_request: true
27+
conn.request :authorization, :basic, api_key, secret_key
28+
conn.headers['Content-Type'] = 'application/json'
29+
end
3830
self.perform_api_call = options.key?(:perform_api_call) ? options[:perform_api_call] : true
3931
end
4032

@@ -54,34 +46,31 @@ def delete(additional_headers = {}, &block)
5446
handle_api_call(:delete, additional_headers, &block)
5547
end
5648

57-
def options
58-
self.adapter.options
59-
end
60-
61-
def concat_urls(*options)
62-
self.adapter.concat_urls(*options)
49+
def concat_urls(suburl)
50+
self.adapter.build_url(suburl.to_s)
6351
end
6452

65-
def url
66-
self.adapter.url
53+
def uri
54+
self.adapter.build_url
6755
end
6856

6957
private
7058

7159
def handle_api_call(method, additional_headers = {}, payload = {}, &block)
72-
formatted_payload = (additional_headers[:content_type] == :json) ? Yajl::Encoder.encode(payload) : payload
60+
formatted_payload = (additional_headers["Content-Type"] == 'application/json') ? Yajl::Encoder.encode(payload) : payload
7361
raise Mailjet::MethodNotAllowed unless method_allowed(method)
7462

7563
if self.perform_api_call
7664
if [:get, :delete].include?(method)
77-
@adapter.send(method, additional_headers, &block)
65+
@adapter.send(method, nil, additional_headers[:params], &block)
7866
else
79-
@adapter.send(method, formatted_payload, additional_headers, &block)
67+
@adapter.send(method, nil, formatted_payload, additional_headers, &block)
8068
end
8169
else
8270
return Yajl::Encoder.encode({'Count' => 0, 'Data' => [mock_api_call: true], 'Total' => 0})
8371
end
84-
rescue RestClient::Exception => e
72+
73+
rescue Faraday::Error => e
8574
handle_exception(e, additional_headers, formatted_payload)
8675
end
8776

@@ -91,41 +80,41 @@ def method_allowed(method)
9180
end
9281

9382
def handle_exception(e, additional_headers, payload = {})
94-
return e.http_body if e.http_headers[:content_type].include?("text/plain")
83+
return e.response_body if e.response_headers[:content_type].include?("text/plain")
9584

9685
params = additional_headers[:params] || {}
9786
formatted_payload = (additional_headers[:content_type] == :json) ? Yajl::Parser.parse(payload) : payload
9887
params = params.merge!(formatted_payload) if formatted_payload.is_a?(Hash)
9988

100-
http_body = if e.http_headers[:content_type].include?("application/json")
101-
e.http_body
89+
response_body = if e.response_headers[:content_type].include?("application/json")
90+
e.response_body
10291
else
10392
"{}"
10493
end
10594

106-
if sent_invalid_email?(e.http_body, @adapter.url)
107-
return e.http_body
95+
if sent_invalid_email?(e.response_body, @adapter.build_url)
96+
return e.response_body
10897
else
10998
raise communication_error(e)
11099
end
111100
end
112101

113102
def communication_error(e)
114103
if e.respond_to?(:response) && e.response
115-
return case e.response.code
104+
return case e.response_status
116105
when Unauthorized::CODE
117-
Unauthorized.new(e.message, e.response)
106+
Unauthorized.new(e.message, e)
118107
when BadRequest::CODE
119-
BadRequest.new(e.message, e.response)
108+
BadRequest.new(e.message, e)
120109
else
121-
CommunicationError.new(e.message, e.response)
110+
CommunicationError.new(e.message, e)
122111
end
123112
end
124113
CommunicationError.new(e.message)
125114
end
126115

127-
def sent_invalid_email?(error_http_body, url)
128-
return false unless url.include?('v3.1/send')
116+
def sent_invalid_email?(error_http_body, uri)
117+
return false unless uri.path.include?('v3.1/send')
129118
return unless error_http_body
130119

131120
parsed_body = Yajl::Parser.parse(error_http_body)
@@ -138,6 +127,5 @@ def sent_invalid_email?(error_http_body, url)
138127
end
139128

140129
class MethodNotAllowed < StandardError
141-
142130
end
143131
end

lib/mailjet/exception/errors.rb

+3-3
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ def initialize(message = nil, response = nil)
5151
@code = if response.nil?
5252
NOCODE
5353
else
54-
response.code
54+
response.response_status
5555
end
5656

5757
api_message = begin
58-
Yajl::Parser.parse(response.body)['ErrorMessage']
58+
Yajl::Parser.parse(response.response_body)['ErrorMessage']
5959
rescue Yajl::ParseError
60-
response.body
60+
response.response_body
6161
rescue NoMethodError
6262
"Unknown API error"
6363
rescue

lib/mailjet/resource.rb

+24-24
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
module Mailjet
1616
module Resource
1717
# define here available options for filtering
18-
OPTIONS = [:version, :url, :perform_api_call, :api_key, :secret_key, :read_timeout, :open_timeout]
18+
OPTIONS = [:version, :url, :perform_api_call, :api_key, :secret_key]
1919

2020
NON_JSON_URLS = ['v3/send/message'] # urls that don't accept JSON input
2121
DATA_URLS = ['plain', 'csv'] # url for send binary data , 'CSVError/text:csv'
@@ -39,21 +39,20 @@ def self.default_connection(options = {})
3939
options[:secret_key] || Mailjet.config.secret_key,
4040
public_operations: public_operations,
4141
read_only: read_only,
42-
perform_api_call: options[:perform_api_call],
43-
open_timeout: options[:open_timeout],
44-
read_timeout: options[:read_timeout])
42+
perform_api_call: options[:perform_api_call])
4543
end
4644

4745
def self.default_headers
4846
if NON_JSON_URLS.include?(self.resource_path) # don't use JSON if Send API
49-
default_headers = { accept: :json, accept_encoding: :deflate }
50-
elsif DATA_URLS.any? { |data_type| default_headers = { content_type: "text/#{data_type}" } if
51-
self.resource_path.include?(data_type)
52-
}
47+
default_headers = { 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate' }
48+
elsif DATA_URLS.any? do |data_type|
49+
default_headers = { 'Content-Type' => "text/#{data_type}" } if self.resource_path.include?(data_type)
50+
end
5351
else
54-
default_headers = { accept: :json, accept_encoding: :deflate, content_type: :json } #use JSON if *not* Send API
52+
# use JSON if *not* Send API
53+
default_headers = {'Content-Type' =>'application/json', 'Accept' =>'application/json', 'Accept-Encoding' => 'deflate'}
5554
end
56-
return default_headers.merge!(user_agent: "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
55+
return default_headers.merge!('User-Agent' => "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
5756
end
5857
end
5958
end
@@ -69,7 +68,7 @@ def all(params = {}, options = {})
6968
opts = define_options(options)
7069
params = format_params(params)
7170
response = connection(opts).get(default_headers.merge!(params: params))
72-
attribute_array = parse_api_json(response)
71+
attribute_array = parse_api_json(response.body)
7372
attribute_array.map{ |attributes| instanciate_from_api(attributes) }
7473
rescue Mailjet::ApiError => error
7574
raise error
@@ -78,7 +77,7 @@ def all(params = {}, options = {})
7877
def count(options = {})
7978
opts = define_options(options)
8079
response_json = connection(opts).get(default_headers.merge!(params: {limit: 1, countrecords: 1}))
81-
response_hash = Yajl::Parser.parse(response_json)
80+
response_hash = Yajl::Parser.parse(response_json.body)
8281
response_hash['Total']
8382
rescue Mailjet::ApiError => error
8483
raise error
@@ -95,7 +94,7 @@ def find(id, job_id = nil, options = {})
9594
opts = define_options(options)
9695
self.resource_path = create_action_resource_path(normalized_id, job_id) if self.action
9796

98-
attributes = parse_api_json(connection(opts)[normalized_id].get(default_headers)).first
97+
attributes = parse_api_json(connection(opts)[normalized_id].get(default_headers).body).first
9998
instanciate_from_api(attributes)
10099

101100
rescue Mailjet::CommunicationError => e
@@ -106,6 +105,14 @@ def find(id, job_id = nil, options = {})
106105
end
107106
end
108107

108+
109+
def find_by_id(id, options = {})
110+
# if action method, ammend url to appropriate id
111+
opts = define_options(options)
112+
self.resource_path = create_action_resource_path(id) if self.action
113+
connection(opts).get(default_headers)
114+
end
115+
109116
def create(attributes = {}, options = {})
110117
# if action method, ammend url to appropriate id
111118
opts = define_options(options)
@@ -139,19 +146,12 @@ def delete(id, options = {})
139146
def send_data(id, binary_data = nil, options = {})
140147
opts = define_options(options)
141148
self.resource_path = create_action_resource_path(id) if self.action
149+
response = connection(opts).post(binary_data, default_headers.merge({'Content-Length' => "#{binary_data.size}", 'Transfer-Encoding' => 'chunked'}))
142150

143-
response_hash = Yajl::Parser.parse(connection(opts).post(binary_data, default_headers))
151+
response_hash = response.respond_to?(:body) ? Yajl::Parser.parse(response.body) : Yajl::Parser.parse(response)
144152
response_hash['ID'] ? response_hash['ID'] : response_hash
145153
end
146154

147-
def find_by_id(id, options = {})
148-
# if action method, ammend url to appropriate id
149-
opts = define_options(options)
150-
self.resource_path = create_action_resource_path(id) if self.action
151-
152-
connection(opts).get(default_headers)
153-
end
154-
155155
def instanciate_from_api(attributes = {})
156156
self.new(attributes.merge!(persisted: true))
157157
end
@@ -284,9 +284,9 @@ def save(options = {})
284284
if opts[:perform_api_call] && !persisted?
285285
# get attributes only for entity creation
286286
self.attributes = if self.resource_path == 'send'
287-
Yajl::Parser.parse(response)
287+
Yajl::Parser.parse(response.body)
288288
else
289-
parse_api_json(response).first
289+
parse_api_json(response.body).first
290290
end
291291
end
292292

lib/mailjet/resources/campaigndraft_detailcontent.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def self.find(id, job_id = nil, options = {})
1111
opts = define_options(options)
1212
self.resource_path = create_action_resource_path(id, job_id) if self.action
1313

14-
raw_data = parse_api_json(connection(opts)[id].get(default_headers))
14+
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)
1515

1616
raw_data.map do |entity|
1717
instanciate_from_api(entity)

lib/mailjet/resources/contact_getcontactslists.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def self.find(id, job_id = nil, options = {})
1111
opts = define_options(options)
1212
self.resource_path = create_action_resource_path(id, job_id) if self.action
1313

14-
raw_data = parse_api_json(connection(opts).get(default_headers))
14+
raw_data = parse_api_json(connection(opts).get(default_headers).body)
1515

1616
raw_data.map do |entity|
1717
instanciate_from_api(entity)

lib/mailjet/resources/messagehistory.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
1212
opts = define_options(options)
1313
self.resource_path = create_action_resource_path(id, job_id) if self.action
1414

15-
raw_data = parse_api_json(connection(opts)[id].get(default_headers))
15+
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)
1616

1717
raw_data.map do |entity|
1818
instanciate_from_api(entity)

lib/mailjet/resources/messageinformation.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
1212
opts = define_options(options)
1313
self.resource_path = create_action_resource_path(id, job_id) if self.action
1414

15-
raw_data = parse_api_json(connection(opts)[id].get(default_headers))
15+
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)
1616

1717
raw_data.map do |entity|
1818
instanciate_from_api(entity)

lib/mailjet/resources/openinformation.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def self.find(id, job_id = nil, options = {})
1212
opts = define_options(options)
1313
self.resource_path = create_action_resource_path(id, job_id) if self.action
1414

15-
raw_data = parse_api_json(connection(opts)[id].get(default_headers))
15+
raw_data = parse_api_json(connection(opts)[id].get(default_headers).body)
1616

1717
raw_data.map do |entity|
1818
instanciate_from_api(entity)

lib/mailjet/resources/template_detailcontent.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def self.find(id, options = {})
1212

1313
opts = define_options(options)
1414
response = connection(opts).get(default_headers)
15-
attributes = parse_api_json(response).first
15+
attributes = parse_api_json(response.body).first
1616

1717
instanciate_from_api(attributes)
1818
rescue Mailjet::CommunicationError => e

lib/mailjet/version.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module Mailjet
2-
VERSION = "1.7.11"
2+
VERSION = "1.8.0"
33
end

mailjet.gemspec

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Gem::Specification.new do |s|
3232

3333
s.add_dependency "activesupport", ">= 5.0.0"
3434
s.add_dependency "rack", ">= 1.4.0"
35-
s.add_dependency "rest-client", ">= 2.1.0"
35+
s.add_dependency 'faraday', "~> 2.1"
3636
s.add_dependency "yajl-ruby"
3737
s.add_development_dependency "actionmailer", ">= 5.0.0"
3838
s.add_development_dependency "rake"

spec/mailer.rb

-4
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,3 @@ def test_email
2121
:template_name => 'test_email.html.erb')
2222
end
2323
end
24-
25-
email = Mailer.test_email
26-
puts email
27-
# email.deliver

0 commit comments

Comments
 (0)