require 'rest_client' require 'singleton' require 'flydata/credentials' require 'flydata/helpers' module Flydata FLYDATA_API_HOST = ENV['FLYDATA_API_HOST'] || 'https://flydata.co' class ApiClient include Singleton include Helpers attr_reader :response attr_accessor :credentials attr_reader :flydata_api_host def initialize @credentials = Flydata::Credentials.new read_flydata_api_host end # row level api def post(path, headers = nil, params=nil) uri = generate_auth_url(path) resource = RestClient::Resource.new(uri, resource_opts(headers)) @response = resource.post(params, :accept => :json) handle_response response end def put(path, params=nil) uri = generate_auth_url(path) resource = RestClient::Resource.new(uri, resource_opts) @response = resource.put(params, :accept => :json) handle_response response end def get(path) uri = generate_auth_url(path) resource = RestClient::Resource.new(uri, resource_opts) @response = resource.get(:accept => :json) handle_response response end # high level api def method_missing(cls_name, *args, &block) method_name = args.shift.to_s require File.join("flydata/api", cls_name.to_s) api_cls = "Flydata::Api::#{cls_name.to_s.camelize}".constantize api_cls.new(self) end def respond_to_missing?(method_name, include_private=false); true end private def read_flydata_api_host if FileTest.exist?(flydata_api_host_file) File.open(flydata_api_host_file, 'r') do |f| @flydata_api_host = f.gets.chomp @flydata_api_host = FLYDATA_API_HOST unless @flydata_api_host and not @flydata_api_host.empty? end else @flydata_api_host = FLYDATA_API_HOST end # delete the '/' @flydata_api_host = @flydata_api_host[0..-2] if @flydata_api_host =~ /\/$/ end def handle_response(response) json_response = JSON.parse(response) if json_response.class == Hash and json_response["success"] == false err_msg = json_response['errors'] ? json_response['errors'].to_s : "Unkown error." raise err_msg elsif json_response.class == Hash and json_response["auth_token"] @credentials.write_credentials(json_response["auth_token"]) end json_response end def resource_opts(headers=nil) # merge headers and default parameter parameters = {} parameters.merge(headers) if headers end def generate_auth_url(path) token = @credentials.token token = '' unless token c = (path && path.include?('?')) ? '&' : '?' "#{@flydata_api_host}#{path}#{c}auth_token=#{token}" end end end