From f25f633fd3d5de21c8175e2591c6481b84df7da2 Mon Sep 17 00:00:00 2001 From: Kuba Suder Date: Sun, 31 Mar 2024 12:43:24 +0300 Subject: [PATCH] allow passing custom headers to requests --- lib/minisky/requests.rb | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/minisky/requests.rb b/lib/minisky/requests.rb index 8c021c0..6715d6c 100644 --- a/lib/minisky/requests.rb +++ b/lib/minisky/requests.rb @@ -39,6 +39,7 @@ def auto_manage_tokens instance_variable_defined?('@auto_manage_tokens') ? @auto_manage_tokens : true end + alias progress default_progress alias progress= default_progress= def base_url @@ -49,10 +50,10 @@ def user @user ||= User.new(config) end - def get_request(method, params = nil, auth: default_auth_mode) + def get_request(method, params = nil, auth: default_auth_mode, headers: nil) check_access if auto_manage_tokens && auth == true - headers = authentication_header(auth) + headers = authentication_header(auth).merge(headers || {}) url = URI("#{base_url}/#{method}") if params && !params.empty? @@ -65,10 +66,12 @@ def get_request(method, params = nil, auth: default_auth_mode) handle_response(response) end - def post_request(method, params = nil, auth: default_auth_mode) + def post_request(method, params = nil, auth: default_auth_mode, headers: nil) check_access if auto_manage_tokens && auth == true - headers = authentication_header(auth).merge({ "Content-Type" => "application/json" }) + headers = authentication_header(auth).merge(headers || {}) + headers["Content-Type"] = "application/json" unless headers.keys.any? { |k| k.downcase == 'content-type' } + body = params ? params.to_json : '' response = Net::HTTP.post(URI("#{base_url}/#{method}"), body, headers) @@ -76,7 +79,7 @@ def post_request(method, params = nil, auth: default_auth_mode) end def fetch_all(method, params = nil, field:, - auth: default_auth_mode, break_when: nil, max_pages: nil, progress: @default_progress) + auth: default_auth_mode, break_when: nil, max_pages: nil, headers: nil, progress: @default_progress) data = [] params = {} if params.nil? pages = 0 @@ -84,7 +87,7 @@ def fetch_all(method, params = nil, field:, loop do print(progress) if progress - response = get_request(method, params, auth: auth) + response = get_request(method, params, auth: auth, headers: headers) records = response[field] cursor = response['cursor']