Sha256: cbee0f94345dc6e429f62016afd669cb172b66c7757a2eff9c6e15079ea1b851

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require 'spike/version'
require 'spike/charge'
require 'spike/error'

class Spike
  API_BASE = 'https://api.spike.cc'
  API_VERSION = '/v1'
  API_URL = API_BASE+API_VERSION

  def initialize(secret_token)
    @secret_token = secret_token
  end

  def charge
    Spike::Charge.new(self)
  end

  def get(request_path:)
    c = build_curl(request_path)
    basic_auth(c)

    c.http_get

    handle_response(c)
    JSON.parse(c.body_str)
  end

  def post(request_path:, request_params:)
    c = build_curl(request_path)
    basic_auth(c)

    curb_post_fields = request_params.map {|k,v| Curl::PostField.content(k,v)}
    c.http_post(c.url, *curb_post_fields)

    handle_response(c)
    JSON.parse(c.body_str)
  end

  private
  def build_curl(request_path)
    c = Curl::Easy.new
    c.url = API_URL + request_path
    c.verbose = true
    c
  end

  def basic_auth(curl)
    curl.http_auth_types = :basic
    curl.username = @secret_token
    curl.password = ''
  end

  def handle_response(curl)
    case curl.status.to_i
    when 400
      raise Spike::BadRequestError, JSON.parse(curl.body_str)['error']['message']
    when 401
      raise Spike::UnauthorizedError
    when 402
      raise Spike::RequestFailedError
    when 500
      raise Spike::ApiServerError
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
spike-ruby-0.0.3 lib/spike.rb