class SFax::Client

Attributes

api_key[R]
encryptor[R]
username[R]

Public Class Methods

new(username:, api_key:, encryption_key:) click to toggle source
# File lib/sfax/client.rb, line 12
def initialize(username:, api_key:, encryption_key:)
  @username = username
  @api_key = api_key
  @encryptor = SFax::Encryptor.new(key: encryption_key)
end

Public Instance Methods

send_fax(fax_number:, file:, recipient_name:) click to toggle source
# File lib/sfax/client.rb, line 18
def send_fax(fax_number:, file:, recipient_name:)
  validate_fax_number fax_number

  response = connection.post SEND_FAX_PATH do |request|
    request.params = {
      'token' => generate_token,
      'ApiKey' => api_key,
      'RecipientFax' => fax_number,
      'RecipientName' => recipient_name,
    }
    request.body = {
      file: Faraday::UploadIO.new(file, 'application/pdf', "#{gen_dt}.pdf")
    }
  end

  response_object = JSON.parse(response.body)
  # TODO: Refactor into proper response objec.
  def response_object.fax_id
    fetch('SendFaxQueueId')
  end

  def response_object.success?
    fetch('isSuccess')
  end

  def response_object.message
    fetch('message')
  end

  response_object.tap do |o|
    raise SendFaxError.new(message: o.message, response: o) unless o.success?
    raise SendFaxError.new(message: o.message, response: o) if o.fax_id.to_s == SEND_FAX_QUEUE_ID_ERROR_VALUE
  end
end

Private Instance Methods

connection() click to toggle source
# File lib/sfax/client.rb, line 55
def connection
  @connection ||= Faraday.new(url: SFAX_URL) do |faraday|
    faraday.request :multipart
    faraday.request :url_encoded
    faraday.adapter Faraday.default_adapter
  end
end
gen_dt() click to toggle source
# File lib/sfax/client.rb, line 69
def gen_dt
  Time.now.utc.iso8601
end
generate_token() click to toggle source
# File lib/sfax/client.rb, line 65
def generate_token
  encryptor.encrypt "Username=#{username}&ApiKey=#{api_key}&GenDT=#{gen_dt}"
end
validate_fax_number(number) click to toggle source
# File lib/sfax/client.rb, line 73
def validate_fax_number(number)
  if number.to_i == 0 || number.length != 11
    raise InvalidFaxNumberError, "Expected an 11 digit fax number. Got: #{number}"
  end
end