lib/onering/api.rb in onering-client-0.0.10 vs lib/onering/api.rb in onering-client-0.0.15
- old
+ new
@@ -1,29 +1,33 @@
require 'net/http'
require 'uri'
require 'json'
require 'yaml'
+require 'addressable/uri'
module Onering
module API
module Errors
class NotConnected < Exception; end
class ClientError < Exception; end
+ class ServerError < Exception; end
end
class Base
+ DEFAULT_BASE="http://onering"
+ DEFAULT_PATH="/api"
+ DEFAULT_OPTIONS={}
+
class<<self
- DEFAULT_URI="http://onering/api"
- DEFAULT_OPTIONS={}
def connect(host=nil)
if host.is_a?(URI)
@_uri = host
elsif host.is_a?(String)
- @_uri = URI.parse(host)
+ @_uri = Addressable::URI.parse("#{host}/#{DEFAULT_PATH}")
else
- @_uri = URI.parse(DEFAULT_URI)
+ @_uri = Addressable::URI.parse("#{DEFAULT_BASE}/#{DEFAULT_PATH}")
end
if @_uri
@_http = Net::HTTP.new(@_uri.host, @_uri.port)
@@ -32,21 +36,21 @@
def request(endpoint, options={})
options = DEFAULT_OPTIONS.merge(options)
request = nil
- qs = options[:fields].collect{|k,v| "#{k}=#{v}" }.join("&") if options[:fields]
- qs = nil if qs and qs.empty?
- endpoint = [endpoint, qs].compact.join('?')
- uri = URI.parse("#{@_uri.to_s}/#{endpoint}")
+ uri = Addressable::URI.parse("#{@_uri.to_s}/#{endpoint}")
+ uri.query_values = options[:fields] if options[:fields]
raise Errors::NotConnected unless @_http
+ #STDERR.puts "DEBUG: Request #{options[:method].to_s.upcase} #{uri.normalize.to_s}"
+
case options[:method]
when :post
request = Net::HTTP::Post.new(uri.request_uri)
- request.body = JSON.dump(options[:data]) if options[:data]
+ request.body = options[:data].to_json if options[:data]
when :delete
request = Net::HTTP::Delete.new(uri.request_uri)
else
@@ -61,12 +65,20 @@
if rv['errors']
msg = "#{rv['errors']['type']}: #{rv['errors']['message']}"
end
- raise ClientError.new(msg)
+ if response.code.to_i >= 500
+ raise Errors::ServerError.new("HTTP #{response.code}: #{msg}")
+ else
+ raise Errors::ClientError.new("HTTP #{response.code}: #{msg}")
+ end
else
- rv = JSON.load(response.body)
+ if response['Content-Type'] == 'application/json'
+ rv = JSON.load(response.body)
+ else
+ rv = response.body
+ end
end
rv
end