-
Notifications
You must be signed in to change notification settings - Fork 29
/
http.rb
315 lines (269 loc) · 10.6 KB
/
http.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
require 'faraday'
require 'uri'
require 'json'
require 'digest/md5'
class HyperResource
## Returns this resource's fully qualified URL. Returns nil when
## `root` or `href` are malformed.
def url
begin
URI.join(self.root, (self.href || '')).to_s
rescue StandardError
nil
end
end
## Performs a GET request to this resource's URL, and returns a
## new resource representing the response.
def get
to_link.get
end
## Performs a GET request to this resource's URL, and returns a
## `Faraday::Response` object representing the response.
def get_response
to_link.get_response
end
## Performs a POST request to this resource's URL, sending all of
## `attributes` as a request body unless an `attrs` Hash is given.
## Returns a new resource representing the response.
def post(attrs=nil)
to_link.post(attrs)
end
## Performs a POST request to this resource's URL, sending all of
## `attributes` as a request body unless an `attrs` Hash is given.
## Returns a `Faraday::Response` object representing the response.
def post_response(attrs=nil)
to_link.post_response(attrs)
end
## Performs a PUT request to this resource's URL, sending all of
## `attributes` as a request body unless an `attrs` Hash is given.
## Returns a new resource representing the response.
def put(*args)
to_link.put(*args)
end
## Performs a PUT request to this resource's URL, sending all of
## `attributes` as a request body unless an `attrs` Hash is given.
## Returns a `Faraday::Response` object representing the response.
def put_response(*args)
to_link.put_response(*args)
end
## Performs a PATCH request to this resource's URL, sending
## `attributes.changed_attributes` as a request body
## unless an `attrs` Hash is given. Returns a new resource
## representing the response.
def patch(*args)
self.to_link.patch(*args)
end
## Performs a PATCH request to this resource's URL, sending
## `attributes.changed_attributes` as a request body
## unless an `attrs` Hash is given.
## Returns a `Faraday::Response` object representing the response.
def patch_response(*args)
self.to_link.patch_response(*args)
end
## Performs a DELETE request to this resource's URL. Returns a new
## resource representing the response.
def delete
to_link.delete
end
## Performs a DELETE request to this resource's URL.
## Returns a `Faraday::Response` object representing the response.
def delete_response
to_link.delete_response
end
## Creates a Link representing this resource. Used for HTTP delegation.
# @private
def to_link(args={})
self.class::Link.new(self,
:href => args[:href] || self.href,
:params => args[:params] || self.attributes)
end
# @private
def create(attrs)
_hr_deprecate('HyperResource#create is deprecated. Please use '+
'#post instead.')
to_link.post(attrs)
end
# @private
def update(*args)
_hr_deprecate('HyperResource#update is deprecated. Please use '+
'#put or #patch instead.')
to_link.put(*args)
end
module Modules
## HyperResource::Modules::HTTP is included by HyperResource::Link.
## It provides support for GET, POST, PUT, PATCH, and DELETE.
## Each method returns a new object which is a kind_of HyperResource.
module HTTP
## Loads and returns the resource pointed to by +href+. The returned
## resource will be blessed into its "proper" class, if
## +self.class.namespace != nil+.
def get
new_resource_from_response(self.get_response)
end
## Performs a GET request on the given link, and returns the
## response as a `Faraday::Response` object.
## Does not parse the response as a `HyperResource` object.
def get_response
## Adding default_attributes to URL query params is not automatic
url = FuzzyURL.new(self.url || '')
query_str = url[:query] || ''
query_attrs = Hash[ query_str.split('&').map{|p| p.split('=')} ]
attrs = (self.resource.default_attributes || {}).merge(query_attrs)
attrs_str = attrs.inject([]){|pairs,(k,v)| pairs<<"#{k}=#{v}"}.join('&')
if attrs_str != ''
url = FuzzyURL.new(url.to_hash.merge(:query => attrs_str))
end
faraday_connection.get(url.to_s)
end
## By default, calls +post+ with the given arguments. Override to
## change this behavior.
def create(*args)
_hr_deprecate('HyperResource::Link#create is deprecated. Please use '+
'#post instead.')
post(*args)
end
## POSTs the given attributes to this resource's href, and returns
## the response resource.
def post(attrs=nil)
new_resource_from_response(post_response(attrs))
end
## POSTs the given attributes to this resource's href, and returns the
## response as a `Faraday::Response` object.
## Does not parse the response as a `HyperResource` object.
def post_response(attrs=nil)
attrs ||= self.resource.attributes
attrs = (self.resource.default_attributes || {}).merge(attrs)
response = faraday_connection.post do |req|
req.body = self.resource.adapter.serialize(attrs)
end
response
end
## By default, calls +put+ with the given arguments. Override to
## change this behavior.
def update(*args)
_hr_deprecate('HyperResource::Link#update is deprecated. Please use '+
'#put or #patch instead.')
put(*args)
end
## PUTs this resource's attributes to this resource's href, and returns
## the response resource. If attributes are given, +put+ uses those
## instead.
def put(attrs=nil)
new_resource_from_response(put_response(attrs))
end
## PUTs this resource's attributes to this resource's href, and returns
## the response as a `Faraday::Response` object.
## Does not parse the response as a `HyperResource` object.
def put_response(attrs=nil)
attrs ||= self.resource.attributes
attrs = (self.resource.default_attributes || {}).merge(attrs)
response = faraday_connection.put do |req|
req.body = self.resource.adapter.serialize(attrs)
end
response
end
## PATCHes this resource's changed attributes to this resource's href,
## and returns the response resource. If attributes are given, +patch+
## uses those instead.
def patch(attrs=nil)
new_resource_from_response(patch_response(attrs))
end
## PATCHes this resource's changed attributes to this resource's href,
## and returns the response as a `Faraday::Response` object.
## Does not parse the response as a `HyperResource` object.
def patch_response(attrs=nil)
attrs ||= self.resource.attributes.changed_attributes
attrs = (self.resource.default_attributes || {}).merge(attrs)
response = faraday_connection.patch do |req|
req.body = self.resource.adapter.serialize(attrs)
end
response
end
## DELETEs this resource's href, and returns the response resource.
def delete
new_resource_from_response(delete_response)
end
## DELETEs this resource's href, and returns the response as a
## `Faraday::Response` object.
## Does not parse the response as a `HyperResource` object.
def delete_response
faraday_connection.delete
end
private
## Returns a raw Faraday connection to this resource's URL, with proper
## headers (including auth). Threadsafe.
def faraday_connection(url=nil)
rsrc = self.resource
url ||= self.url
headers = (rsrc.headers_for_url(url) || {}).merge(self.headers)
auth = rsrc.auth_for_url(url) || {}
key = ::Digest::MD5.hexdigest({
'faraday_connection' => {
'url' => url,
'headers' => headers,
'ba' => auth[:basic]
}
}.to_json)
return Thread.current[key] if Thread.current[key]
fo = rsrc.faraday_options_for_url(url) || {}
fc = Faraday.new(fo.merge(:url => url))
fc.headers.merge!('User-Agent' => rsrc.user_agent)
fc.headers.merge!(headers)
if ba=auth[:basic]
fc.basic_auth(*ba)
end
Thread.current[key] = fc
end
## Given a Faraday::Response object, create a new resource
## object to represent it. The new resource will be in its
## proper class according to its configured `namespace` and
## the response's detected data type.
def new_resource_from_response(response)
status = response.status
is_success = (status / 100 == 2)
adapter = self.resource.adapter || HyperResource::Adapter::HAL_JSON
body = nil
unless empty_body?(response.body)
begin
body = adapter.deserialize(response.body)
rescue StandardError => e
if is_success
raise HyperResource::ResponseError.new(
"Error when deserializing response body",
:response => response,
:cause => e
)
end
end
end
new_rsrc = resource.new_from(:link => self,
:body => body,
:response => response)
if status / 100 == 2
return new_rsrc
elsif status / 100 == 3
raise NotImplementedError,
"HyperResource has not implemented redirection."
elsif status / 100 == 4
raise HyperResource::ClientError.new(status.to_s,
:response => response,
:body => body)
elsif status / 100 == 5
raise HyperResource::ServerError.new(status.to_s,
:response => response,
:body => body)
else ## 1xx? really?
raise HyperResource::ResponseError.new("Unknown status #{status}",
:response => response,
:body => body)
end
end
def empty_body?(body)
return true if body.nil?
return true if body.respond_to?(:empty?) && body.empty?
return true if body.class == String && body =~ /^['"]+$/ # special case for status code with optional body, example Grape API with status 405
false
end
end
end
end