module Roqua module CoreApi module Sessions class AuthSession attr_reader :core_site attr_reader :default_timeout # timeout for requests in seconds def initialize(core_site: ENV.fetch('CORE_SITE'), timeout: nil) @core_site = core_site @default_timeout = timeout end def get(path, timeout: default_timeout, **params) perform_request_or_fail do HTTParty.get full_url_for(path), query_string_options('GET', path, params, timeout: timeout) end end def post(path, timeout: default_timeout, **params) perform_request_or_fail do HTTParty.post full_url_for(path), json_body_options('POST', path, params, timeout: timeout) end end def patch(path, timeout: default_timeout, **params) perform_request_or_fail do HTTParty.patch full_url_for(path), json_body_options('PATCH', path, params, timeout: timeout) end end def delete(path, timeout: default_timeout, **params) HTTParty.delete full_url_for(path), query_string_options('DELETE', path, params, timeout: timeout) end private def perform_request_or_fail(&block) response = yield case response.code when 200..299, 422 response when 401 access_denied(response) else fail(response.parsed_response.to_s || 'error') end end def json_body_options(request_method, path, params, timeout:) {headers: headers(request_method, path, params).merge('Content-Type' => 'application/json'), body: params.to_json, basic_auth: basic_auth, timeout: timeout} end def query_string_options(request_method, path, params, timeout:) {headers: headers(request_method, path, params), query: params, basic_auth: basic_auth, timeout: timeout} end def full_url_for(path) core_site + api_base + path + '.json' end def api_base '/api/v1' end def headers(_request_method, _path, _params) {} end def basic_auth end end end end end