-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.rb
59 lines (46 loc) · 1.57 KB
/
request.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true
require 'net/http'
require 'uri'
module Tikkie
module Api
module V1
# Make authenticated HTTP requests to the Tikkie API.
class Request
def initialize(config)
@config = config
end
def get(path, params = {})
uri = URI.parse(File.join(@config.api_url, path))
uri.query = URI.encode_www_form(params) unless params.empty?
request = Net::HTTP::Get.new(uri)
request["Api-Key"] = @config.api_key
request["Authorization"] = "Bearer #{access_token}"
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
response
end
def post(path, params = {})
uri = URI.parse(File.join(@config.api_url, path))
request = Net::HTTP::Post.new(uri)
request["Api-Key"] = @config.api_key
request["Authorization"] = "Bearer #{access_token}"
request["Content-Type"] = "application/json"
request.body = params.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
response
end
private
def access_token
if @access_token.nil? || @access_token.expired?
@authentication ||= Tikkie::Api::V1::Authentication.new(@config)
@access_token = @authentication.authenticate
end
@access_token.token
end
end
end
end
end