Module: LivePaper::HttpClient
- Included in:
- BaseObject
- Defined in:
- lib/live_paper/http_client.rb
Constant Summary collapse
- LP_API_HOST =
"https://www.livepaperapi.com"- AUTH_URL =
"#{LP_API_HOST}/auth/token"
Instance Method Summary collapse
- #check_response(response, allow_codes) ⇒ Object
- #http_request(url, method) ⇒ Object
- #request_access_token ⇒ Object
- #request_handling_auth(url, method) ⇒ Object
- #send_request(request, options = {}) ⇒ Object
Instance Method Details
#check_response(response, allow_codes) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/live_paper/http_client.rb', line 21 def check_response(response, allow_codes) status = response.code.to_i raise NotAuthenticatedError.new("Unauthorized") if status == 401 unless allow_codes.include?(status) raise "Request failed with code #{status}" end end |
#http_request(url, method) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/live_paper/http_client.rb', line 58 def http_request(url, method) uri = URI.parse(url) set_http uri case method.to_s.upcase when 'POST' Net::HTTP::Post.new(uri.request_uri) when 'GET' Net::HTTP::Get.new(uri.request_uri) when 'PUT' Net::HTTP::Put.new(uri.request_uri) when 'DELETE' Net::HTTP::Delete.new(uri.request_uri) else raise "Method '#{method}' not supported." end end |
#request_access_token ⇒ Object
48 49 50 51 52 53 54 55 56 |
# File 'lib/live_paper/http_client.rb', line 48 def request_access_token request = http_request(AUTH_URL, 'POST') request['Authorization'] = "Basic #{$lpp_basic_auth}" request['Content-Type'] = 'application/x-www-form-urlencoded' request.body = 'grant_type=client_credentials&scope=all' response = @http.request(request) parsed = JSON.parse(response.body) @access_token = parsed['accessToken'] end |
#request_handling_auth(url, method) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/live_paper/http_client.rb', line 29 def request_handling_auth(url, method) tries = 0 begin request_access_token unless @access_token request = http_request(url, method) request['Authorization'] = "Bearer #{@access_token}" request['Accept'] = "application/json" yield request rescue NotAuthenticatedError => e tries += 1 if tries < 3 @access_token = nil retry else raise e end end end |
#send_request(request, options = {}) ⇒ Object
12 13 14 15 16 17 18 19 |
# File 'lib/live_paper/http_client.rb', line 12 def send_request(request, ={}) request['Content-type'] = [:content_type] if [:content_type] request.body = [:body] if [:body] [:allow_codes] ||= [200,201] response = @http.request(request) check_response(response, [:allow_codes]) response end |