class SendGridMailer::Api

Public Class Methods

new(api_key) click to toggle source
# File lib/send_grid_mailer/api.rb, line 5
def initialize(api_key)
  @api_key = api_key || raise(SendGridMailer::InvalidApiKey)
end

Public Instance Methods

get_template(sg_definition) click to toggle source
# File lib/send_grid_mailer/api.rb, line 14
def get_template(sg_definition)
  response = sg_api.client.templates._(sg_definition.mail.template_id).get()
  handle_response(response, :template)
end
send_mail(sg_definition) click to toggle source
# File lib/send_grid_mailer/api.rb, line 9
def send_mail(sg_definition)
  response = sg_api.client.mail._('send').post(request_body: sg_definition.to_json)
  handle_response(response, :mail)
end

Private Instance Methods

handle_response(response, api_call_type) click to toggle source
# File lib/send_grid_mailer/api.rb, line 21
def handle_response(response, api_call_type)
  status_code = response.status_code.to_i
  if status_code.between?(400, 600)
    errors = response_errors(response)
    log_api_error_response(status_code, errors, api_call_type)
    raise SendGridMailer::ApiError.new(status_code, errors)
  end

  log_api_success_response(status_code, api_call_type)
  response
end
response_errors(response) click to toggle source
# File lib/send_grid_mailer/api.rb, line 33
def response_errors(response)
  body = JSON.parse(response.body)
  body["errors"] || [{ "message" => body["error"] }]
end
sg_api() click to toggle source
# File lib/send_grid_mailer/api.rb, line 38
def sg_api
  @sg_api ||= SendGrid::API.new(api_key: @api_key)
end