module YtApi
Public Instance Methods
Source
# File lib/yt_api.rb, line 55 def auth_headers(access_token) { "Authorization" => "Bearer #{access_token}" } end
Source
# File lib/yt_api.rb, line 47 def build_url(path, params = {}) base = path.to_s.start_with?("http") ? path.to_s : "#{YtConfig::API_BASE}#{path}" return base if params.empty? separator = base.include?("?") ? "&" : "?" "#{base}#{separator}#{URI.encode_www_form(params)}" end
Source
# File lib/yt_api.rb, line 31 def delete(path, access_token:, params: {}, fetch: nil) url = build_url(path, params) response = request(method: "DELETE", url: url, headers: auth_headers(access_token), fetch: fetch) parse_response(response, allow_empty: true) end
Source
# File lib/yt_api.rb, line 13 def get(path, access_token:, params: {}, fetch: nil) url = build_url(path, params) body = request(method: "GET", url: url, headers: auth_headers(access_token), fetch: fetch) parse_response(body) end
Source
# File lib/yt_api.rb, line 75 def parse_response(body, allow_empty: false) return { success: true } if allow_empty && body.to_s.strip.empty? data = body.is_a?(String) ? JSON.parse(body) : body if data.is_a?(Hash) && data["error"] message = data.dig("error", "message").to_s message = data.dig("error", "errors", 0, "message").to_s if message.empty? return { success: false, error: message.empty? ? "YouTube API error" : message } end { success: true, data: data } rescue JSON::ParserError { success: false, error: "Invalid YouTube API response" } end
Source
# File lib/yt_api.rb, line 19 def post(path, access_token:, body:, params: {}, fetch: nil) url = build_url(path, params) response = request( method: "POST", url: url, headers: auth_headers(access_token).merge("Content-Type" => "application/json"), body: JSON.generate(body), fetch: fetch ) parse_response(response) end
Source
# File lib/yt_api.rb, line 59 def request(method:, url:, headers: {}, body: nil, fetch: nil) if fetch return fetch.call(url, method: method, headers: headers, body: body) end uri = URI(url) request_class = method.to_s.upcase == "POST" ? Net::HTTP::Post : (method.to_s.upcase == "DELETE" ? Net::HTTP::Delete : Net::HTTP::Get) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == "https" request = request_class.new(uri) headers.each { |key, value| request[key] = value } request["User-Agent"] = RabbotHttp::DEFAULT_USER_AGENT request.body = body if body http.request(request).body end
Source
# File lib/yt_api.rb, line 37 def with_access_token(account:, fetch: nil) token = YtOAuth.refresh_access_token(account: account, fetch: fetch) return token unless token[:success] result = yield(token[:access_token]) return result if result[:success] result end