demarches-normaliennes/app/lib/sendinblue/api.rb

74 lines
1.4 KiB
Ruby
Raw Normal View History

2019-03-07 16:30:25 +01:00
class Sendinblue::Api
def self.new_properly_configured!
api = self.new
if !api.properly_configured?
raise StandardError, 'Sendinblue API is not properly configured'
end
api
end
def initialize
@failures = []
end
def properly_configured?
client_key.present?
end
2019-10-01 17:28:06 +02:00
def update_contact(email, attributes = {})
req = post_api_request('contacts', email: email, attributes: attributes, updateEnabled: true)
2019-03-07 16:30:25 +01:00
req.on_complete do |response|
if !response.success?
push_failure("Error while updating identity for administrateur '#{email}' in Sendinblue: #{response.response_code} '#{response.body}'")
end
end
hydra.queue(req)
end
def run
hydra.run
@hydra = nil
flush_failures
end
private
def hydra
2019-10-01 17:28:06 +02:00
@hydra ||= Typhoeus::Hydra.new(max_concurrency: 50)
2019-03-07 16:30:25 +01:00
end
def push_failure(failure)
@failures << failure
end
def flush_failures
failures = @failures
@failures = []
if failures.present?
raise StandardError, failures.join(', ')
end
end
2019-10-01 17:28:06 +02:00
def post_api_request(path, body)
url = "#{SENDINBLUE_API_V3_URL}/#{path}"
2019-03-07 16:30:25 +01:00
Typhoeus::Request.new(
url,
method: :post,
body: body.to_json,
headers: headers
)
end
def headers
{
2019-10-01 17:28:06 +02:00
'api-key': client_key,
2019-03-07 16:30:25 +01:00
'Content-Type': 'application/json; charset=UTF-8'
}
end
def client_key
2019-10-01 17:28:06 +02:00
Rails.application.secrets.sendinblue[:api_v3_key]
2019-03-07 16:30:25 +01:00
end
end