/
http_request.rb
112 lines (96 loc) · 2.72 KB
/
http_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
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
109
110
111
112
# frozen_string_literal: true
require 'httparty'
require 'meilisearch/error'
module MeiliSearch
class HTTPRequest
include HTTParty
attr_reader :options
def initialize(url, api_key = nil, options = {})
@base_url = url
@api_key = api_key
@options = options
@headers = {
'Content-Type' => 'application/json',
'X-Meili-API-Key' => api_key
}.compact
@headers_no_body = {
'X-Meili-API-Key' => api_key
}.compact
end
def http_get(relative_path = '', query_params = {})
send_request(
proc { |path, config| self.class.get(path, config) },
relative_path,
query_params: query_params,
headers: @headers_no_body
)
end
def http_post(relative_path = '', body = nil, query_params = nil)
send_request(
proc { |path, config| self.class.post(path, config) },
relative_path,
query_params: query_params,
body: body,
headers: @headers
)
end
def http_put(relative_path = '', body = nil, query_params = nil)
send_request(
proc { |path, config| self.class.put(path, config) },
relative_path,
query_params: query_params,
body: body,
headers: @headers
)
end
def http_delete(relative_path = '')
send_request(
proc { |path, config| self.class.delete(path, config) },
relative_path,
headers: @headers_no_body
)
end
private
SNAKE_CASE = /[^a-zA-Z0-9]+(.)/.freeze
def send_request(http_method, relative_path, query_params: nil, body: nil, headers: nil)
config = http_config(query_params, body, headers)
begin
response = http_method.call(@base_url + relative_path, config)
rescue Errno::ECONNREFUSED => e
raise CommunicationError, e.message
end
validate(response)
end
def http_config(query_params, body, headers)
body = transform_attributes(body).to_json
{
headers: headers,
query: query_params,
body: body,
timeout: @options[:timeout] || 1,
max_retries: @options[:max_retries] || 0
}.compact
end
def transform_attributes(body)
case body
when Array
body.map { |item| transform_attributes(item) }
when Hash
parse(body)
else
body
end
end
def parse(body)
body
.transform_keys(&:to_s)
.transform_keys do |key|
key.include?('_') ? key.downcase.gsub(SNAKE_CASE, &:upcase).gsub('_', '') : key
end
end
def validate(response)
raise ApiError.new(response.code, response.message, response.body) unless response.success?
response.parsed_response
end
end
end