36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
# File 'lib/brivo/api/http.rb', line 36
def http_request path, method: :get, params: {}, offset: nil
attempts = 0
begin
attempts += 1
uri = "#{API_URL}/#{path}"
parsed_uri = URI.parse(uri)
if offset
if parsed_uri.query.nil?
parsed_uri.query = "pageSize=#{PAGE_SIZE}&offset=#{offset}"
else
parsed_uri.query = "#{parsed_uri.query}&pageSize=#{PAGE_SIZE}&offset=#{offset}"
end
end
http_methods = {
get: Net::HTTP::Get,
post: Net::HTTP::Post,
put: Net::HTTP::Put,
delete: Net::HTTP::Delete
}
response = Net::HTTP.start(parsed_uri.host, parsed_uri.port, DEFAULT_HTTPS_SETTINGS) do |https|
request = http_methods[method].new(parsed_uri)
request.body = params.to_json
if @access_token.nil? || monotonic_time > @access_token_expiry
set_access_token
end
request['Content-Type'] = 'application/json'
request['Authorization'] = "bearer #{@access_token}"
request['api-key'] = api_key
https.request(request)
end
case response.code.to_i
when 200
JSON.parse(response.body)
when 201
JSON.parse(response.body)
when 204
true
when 400
raise Brivo::Error::BadRequest
when 401
raise Brivo::Error::Unauthorized
when 403
raise Brivo::Error::Forbidden
when 404
raise Brivo::Error::NotFound
when 415
raise Brivo::Error::UnsupportedMediaType
when 418
raise Brivo::Error::IsATeapot
when 503
raise Brivo::Error::ServiceUnavailable
when 596
raise Brivo::Error::ServiceNotFound
else
raise Brivo::Error::UnkownResponse
end
rescue StandardError
if attempts > MAX_RETRIES
raise
else
retry
end
end
end
|