Sha256: a917f31ac24586c4d737e23a87536a31798bea6a3d33e810a02273d5959f0ba5

Contents?: true

Size: 1.89 KB

Versions: 3

Compression:

Stored size: 1.89 KB

Contents

require 'rest-client'
require 'yajl'
require 'timeout'

# Internal: Handles HTTP requests/responses to the keikoku API
#
# This class is meant to be used internally by Keikokuc
class Keikokuc::Client
  include HandlesTimeout

  InvalidNotification = Class.new
  Unauthorized = Class.new

  attr_accessor :producer_api_key

  def initialize(opts = {})
    @producer_api_key = opts[:producer_api_key]
  end

  # Internal: posts a new notification to keikoku
  #
  # attributes - a hash containing notification attributes
  #
  # Examples
  #
  #   client = Keikokuc::Client.new(producer_api_key: 'abcd')
  #   response, error = client.post_notification(message: 'hello')
  #
  # Returns
  #
  # two objects:
  #   The response as a hash
  #   The error if any (nil if no error)
  #
  # Possible errors include:
  #
  # * `Client::Timeout` if the request takes longer than 5 seconds
  # * `Client::InvalidNotification` if the response indicates
  #   invalid notification attributes
  # * `Client::Unauthorized` if API key auth fails
  def post_notification(attributes)
    begin
      response = notifications_api.post(encode_json(attributes), {'X-KEIKOKU-AUTH' => producer_api_key})
      [parse_json(response), nil]
    rescue RestClient::UnprocessableEntity => e
      [parse_json(e.response), InvalidNotification]
    rescue RestClient::Unauthorized => e
      [{}, Unauthorized]
    end
  end
  handle_timeout :post_notification

private
  def notifications_api # :nodoc:
    @notifications_api ||= RestClient::Resource.new(api_url)
  end

  def api_url # :nodoc:
    "https://keikoku.herokuapp.com/api/v1/notifications"
  end

  def encode_json(hash) # :nodoc:
    Yajl::Encoder.encode(hash)
  end

  def parse_json(data) # :nodoc:
    symbolize_keys(Yajl::Parser.parse(data)) if data
  end

  def symbolize_keys(hash) # :nodoc:
    hash.inject({}) do |result, (k, v)|
      result[k.to_sym] = v
      result
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
keikokuc-0.0.3 lib/keikokuc/client.rb
keikokuc-0.0.2 lib/keikokuc/client.rb
keikokuc-0.0.1 lib/keikokuc/client.rb