require 'questrade_api/modules/util'
require 'faraday'
require 'json'
module QuestradeApi
module REST
class Base
include QuestradeApi::Util
BASE_ENDPOINT = '/v1'.freeze
attr_accessor :connection, :raw_body, :endpoint,
:authorization, :data
def initialize(authorization)
@authorization = authorization
@connection =
self.class.connection(url: url,
access_token: @authorization.access_token)
end
def url
authorization.url
end
def self.connection(params = {})
Faraday.new(params[:url]) do |faraday|
faraday.adapter Faraday.default_adapter
faraday.['Content-Type'] = 'application/json'
faraday.['Authorization'] = "Bearer #{params[:access_token]}"
end
end
protected
def build_data(data)
hash = hash_to_snakecase(data)
@data = OpenStruct.new(hash)
end
def build_attributes(response)
@raw_body = JSON.parse(response.body)
end
def fetch(params = {})
response = @connection.get do |req|
req.path = params[:endpoint] || self.class.endpoint
params.fetch(:params, []).each do |key, value|
req.params[key] = value
end
end
build_attributes(response) if response.status == 200
response
end
class << self
def fetch(params = {})
connection = connection(params)
connection.get do |req|
req.path = params[:endpoint]
params.fetch(:params, []).each do |key, value|
req.params[key] = value
end
end
end
end
end
end
end