require 'fanforce/errors' require 'fanforce/utils' class Fanforce ######################################################################## def initialize(auth_key_or_hash=nil) auth(auth_key_or_hash) if auth_key_or_hash.present? 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 = MultiJson.load(response, :symbolize_keys => symbolize_keys) 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_key_or_hash=nil) if auth_key_or_hash.present? key = auth_key_or_hash.is_a?(Hash) ? auth_key_or_hash.symbolize_keys[:key] : auth_key_or_hash @auth_hash = {key: key} if key.present? end @auth_hash end def valid_auth? @auth_hash.present? and @auth_hash[:key].present? end def apply_auth(params) params.merge(@auth_hash || {}) end def complete_path(path) 'http://' + $API_DOMAIN + path end def is_valid_install_request(params) Utils.is_valid_install_request(params) end def is_invalid_install_request(params) !is_valid_install_request(params) end def is_valid_uninstall_request(params) Utils.is_valid_uninstall_request(params) end def is_invalid_uninstall_request(params) !is_valid_uninstall_request(params) end def is_valid_request(params) Utils.is_valid_request(params) end def is_invalid_request(params) !is_valid_request(params) end def parse_params(params) Utils.parse_params(params) end def parse_url(raw_url) Utils.parse_url(raw_url) end end