require 'fanforce/errors' require 'fanforce/utils' require 'rest-client' class Fanforce include Fanforce::Utils ######################################################################## def initialize(auth_key_or_hash=nil) auth(auth_key_or_hash) if present?(auth_key_or_hash) end def get(path, requestParams={}) path = complete_path(path) query = apply_auth(requestParams) RestClient.get(path, {:params => query, :accept => :json}) do |response, request, result, &block| handle_response(response, request, path, query) end end def post(path, requestParams={}) path = complete_path(path) query = apply_auth(requestParams) RestClient.post(path, query, {:accept => :json}) do |response, request, result, &block| handle_response(response, request, path, query) end end def put(path, requestParams={}) path = complete_path(path) query = apply_auth(requestParams) RestClient.put(path, query, {:accept => :json}) do |response, request, result, &block| handle_response(response, request, path, query) end end def delete(path, requestParams={}) path = complete_path(path) query = apply_auth(requestParams) RestClient.delete(path, {:query => query, :accept => :json}) do |response, request, result, &block| handle_response(response, request, path, query) end end def handle_response(response, request, path, query) case response.code when 200, 201 begin response = decode_json(response) rescue raise UnknownError.new(response, request, path, query) end when 400 raise BadRequestError.new(response, request, path, query) when 403 raise ForbiddenError.new(response, request, path, query) when 404 raise NotFoundError.new(response, request, path, query) when 422 raise UnprocessableEntityError.new(response, request, path, query) else raise UnknownError.new(response, request, path, query) end response end def auth(auth_hash=nil) if present?(auth_hash) auth_hash = auth_hash.is_a?(Hash) ? auth_hash.symbolize_keys : {api_key: auth_hash} @auth_hash[:api_key] if present?(auth_hash[:api_key]) @auth_hash[:fanforce_id] if present?(auth_hash[:fanforce_id]) end @auth_hash end def valid_auth? present?(@auth_hash) and present?(@auth_hash[:api_key]) end def apply_auth(params) params.merge(@auth_hash || {}) end def complete_path(path) 'http://' + $API_DOMAIN + path end end