hyperclient 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,38 @@
1
1
  require 'addressable'
2
2
 
3
3
  module Hyperclient
4
+ # Public: Exception that is raised when iterating a link whose resource
5
+ # links back to itself under the same name, which would otherwise recurse
6
+ # forever.
7
+ class SelfReferencingLinkError < StandardError
8
+ def initialize(key, url)
9
+ super("The #{key} link at #{url} links back to itself, use _embedded to iterate over embedded items.")
10
+ end
11
+ end
12
+
13
+ # Public: Exception that is raised before sending a request with a method
14
+ # that the most recent response for the same Link excluded from its Allow
15
+ # header.
16
+ class MethodNotAllowedError < StandardError
17
+ # Public: Returns the upper-case String HTTP method that was refused.
18
+ attr_reader :http_method
19
+
20
+ # Public: Returns the String url of the Link.
21
+ attr_reader :url
22
+
23
+ # Public: Returns the Array of upper-case String methods that the server
24
+ # allows.
25
+ attr_reader :allowed
26
+
27
+ def initialize(http_method, url, allowed)
28
+ @http_method = http_method
29
+ @url = url
30
+ @allowed = allowed
31
+ allows = allowed.empty? ? 'no methods' : "only #{allowed.join(', ')}"
32
+ super("#{http_method} is not allowed on #{url}, the server allows #{allows}.")
33
+ end
34
+ end
35
+
4
36
  # Internal: The Link is used to let a Resource interact with the API.
5
37
  #
6
38
  class Link
@@ -13,12 +45,29 @@ module Hyperclient
13
45
  # entry_point - The EntryPoint object to inject the configuration.
14
46
  # uri_variables - The optional Hash with the variables to expand the link
15
47
  # if it is templated.
16
- def initialize(key, link, entry_point, uri_variables = nil)
48
+ # query_params - The optional Hash with query parameters to add to the
49
+ # link's URL.
50
+ def initialize(key, link, entry_point, uri_variables = nil, query_params = nil)
17
51
  @key = key
18
52
  @link = link
19
53
  @entry_point = entry_point
20
54
  @uri_variables = uri_variables
55
+ @query_params = query_params
21
56
  @resource = nil
57
+ @allow = nil
58
+ end
59
+
60
+ # Internal: Parses the Allow header from response headers.
61
+ #
62
+ # headers - The Hash-like response headers, or nil.
63
+ #
64
+ # Returns nil when there is no Allow header, otherwise an Array of
65
+ # upper-case String methods, which is empty when the header is empty.
66
+ def self.parse_allow(headers)
67
+ value = headers && (headers['Allow'] || headers['allow'])
68
+ return if value.nil?
69
+
70
+ Array(value).join(',').split(',').map { |m| m.strip.upcase }.reject(&:empty?).uniq
22
71
  end
23
72
 
24
73
  # Public: Each implementation to allow the class to use the Enumerable
@@ -30,6 +79,8 @@ module Hyperclient
30
79
  current = self
31
80
  while current
32
81
  coll = current.respond_to?(@key) ? current.send(@key) : _resource
82
+ raise SelfReferencingLinkError.new(@key, current._url) if current.self_referencing?(coll)
83
+
33
84
  coll.each(&block)
34
85
  break unless current._links[:next]
35
86
 
@@ -54,14 +105,22 @@ module Hyperclient
54
105
  #
55
106
  # Returns a new Link with the expanded variables.
56
107
  def _expand(uri_variables = {})
57
- self.class.new(@key, @link, @entry_point, uri_variables)
108
+ self.class.new(@key, @link, @entry_point, uri_variables, @query_params)
109
+ end
110
+
111
+ # Public: Adds query parameters to the Link's URL, whether or not the link
112
+ # is templated or declares them. Parameters with nil values are dropped.
113
+ #
114
+ # query_params - The Hash with the query parameters to add.
115
+ #
116
+ # Returns a new Link with the query parameters.
117
+ def _query(query_params = {})
118
+ self.class.new(@key, @link, @entry_point, @uri_variables, (@query_params || {}).merge(query_params))
58
119
  end
59
120
 
60
121
  # Public: Returns the url of the Link.
61
122
  def _url
62
- return @link['href'] unless _templated?
63
-
64
- @url ||= _uri_template.expand(@uri_variables || {}).to_s
123
+ @url ||= _add_query_params(_templated? ? _uri_template.expand(@uri_variables || {}).to_s : @link['href'])
65
124
  end
66
125
 
67
126
  # Public: Returns an array of variables from the URITemplate.
@@ -101,6 +160,25 @@ module Hyperclient
101
160
  @link['hreflang']
102
161
  end
103
162
 
163
+ # Public: Returns the methods listed in the Allow header of the most
164
+ # recent response for this Link, as upper-case Strings.
165
+ #
166
+ # Returns nil if no response has been received yet or the most recent
167
+ # response did not carry an Allow header.
168
+ def _allow
169
+ @allow&.dup
170
+ end
171
+
172
+ # Public: Indicates if the server allows the given method on this Link,
173
+ # according to the Allow header of the most recent response.
174
+ #
175
+ # method - A Symbol or String HTTP method, case-insensitive.
176
+ #
177
+ # Returns true if the method is allowed or no Allow header was received.
178
+ def _allow?(method)
179
+ @allow.nil? || @allow.include?(method.to_s.upcase)
180
+ end
181
+
104
182
  def _resource
105
183
  @resource || _get
106
184
  end
@@ -161,6 +239,7 @@ module Hyperclient
161
239
  return unless @key && _resource.respond_to?(@key)
162
240
 
163
241
  @delegate ||= _resource.send(@key)
242
+ return if self_referencing?(@delegate)
164
243
  return unless @delegate&.respond_to?(method.to_s)
165
244
 
166
245
  @delegate.send(method, *args, &block)
@@ -169,13 +248,21 @@ module Hyperclient
169
248
  # Internal: Accessory method to allow the link respond to the
170
249
  # methods that will hit method_missing.
171
250
  def respond_to_missing?(method, _include_private = false)
172
- if @key && _resource.respond_to?(@key) && (delegate = _resource.send(@key)) && delegate.respond_to?(method.to_s)
251
+ if @key && _resource.respond_to?(@key) && (delegate = _resource.send(@key)) &&
252
+ !self_referencing?(delegate) && delegate.respond_to?(method.to_s)
173
253
  true
174
254
  else
175
255
  _resource.respond_to?(method.to_s)
176
256
  end
177
257
  end
178
258
 
259
+ # Internal: Indicates if the given object is a Link to this same URL,
260
+ # following which would recurse forever.
261
+ def self_referencing?(other)
262
+ other.is_a?(Link) && other._url == _url
263
+ end
264
+ protected :self_referencing?
265
+
179
266
  # Internal: avoid delegating to resource
180
267
  #
181
268
  # #to_ary is called for implicit array coercion (such as parallel assignment
@@ -189,11 +276,49 @@ module Hyperclient
189
276
  @uri_template ||= Addressable::Template.new(@link['href'])
190
277
  end
191
278
 
279
+ # Internal: Appends the query parameters to the URL, keeping its existing
280
+ # query string and fragment.
281
+ def _add_query_params(url)
282
+ params = (@query_params || {}).compact
283
+ return url if params.empty?
284
+
285
+ uri = Addressable::URI.parse(url)
286
+ uri.query = [uri.query, Addressable::URI.form_encode(params)].compact.reject(&:empty?).join('&')
287
+ uri.to_s
288
+ end
289
+
290
+ # Internal: Raises MethodNotAllowedError if the most recent response for
291
+ # this Link excluded the method from its Allow header. OPTIONS is always
292
+ # sent, so that callers can rediscover the allowed methods.
293
+ def ensure_allowed!(method)
294
+ return if method == :options || _allow?(method) || !@entry_point.enforce_allowed_methods?
295
+
296
+ raise MethodNotAllowedError.new(method.to_s.upcase, _url, @allow.dup)
297
+ end
298
+
192
299
  def http_method(method, body = nil)
193
- @resource = begin
300
+ ensure_allowed!(method)
301
+
302
+ begin
194
303
  response = @entry_point.connection.run_request(method, _url, body, nil)
195
- Resource.new(response.body, @entry_point, response)
304
+ rescue Faraday::Error => e
305
+ @allow = Link.parse_allow(e.response_headers) if e.response
306
+ raise
196
307
  end
308
+
309
+ @allow = Link.parse_allow(response.headers)
310
+ resource = Resource.new(response.body, @entry_point, response)
311
+
312
+ # Only cache GET responses. Caching the response of a mutating
313
+ # request (POST/PUT/PATCH/DELETE) as `@resource` would make
314
+ # subsequent delegated calls (e.g. `#each`, `method_missing`) see
315
+ # the stale mutation response instead of fetching a fresh
316
+ # resource, requiring users to create a new client between a
317
+ # `_post` and a `_get`. See #107.
318
+ @resource = resource if method == :get
319
+ @delegate = nil
320
+
321
+ resource
197
322
  end
198
323
  end
199
324
  end
@@ -62,10 +62,37 @@ module Hyperclient
62
62
  _response&.status
63
63
  end
64
64
 
65
+ # Public: Returns the methods listed in the Allow header of the response
66
+ # that created this resource, as upper-case Strings, or nil if there is no
67
+ # response or it did not carry an Allow header.
68
+ def _allow
69
+ Link.parse_allow(_response&.headers)
70
+ end
71
+
72
+ # Public: Indicates if the response that created this resource allows the
73
+ # given Symbol or String HTTP method, case-insensitive. Returns true if
74
+ # there is no Allow header.
75
+ def _allow?(method)
76
+ allow = _allow
77
+ allow.nil? || allow.include?(method.to_s.upcase)
78
+ end
79
+
65
80
  def [](name)
66
81
  send(name) if respond_to?(name)
67
82
  end
68
83
 
84
+ # Public: Returns the attributes of the Resource as a Hash.
85
+ #
86
+ # Delegates explicitly (rather than relying on method_missing) since
87
+ # Array also defines #to_h (but not #to_hash), which meant the
88
+ # `Array.method_defined?(method)` guard in method_missing let #to_hash
89
+ # through but silently swallowed #to_h, returning nil instead of the
90
+ # attributes hash.
91
+ def to_h
92
+ _attributes.to_h
93
+ end
94
+ alias to_hash to_h
95
+
69
96
  def fetch(key, *args)
70
97
  return self[key] if respond_to?(key)
71
98
 
@@ -1,3 +1,3 @@
1
1
  module Hyperclient
2
- VERSION = '2.0.0'.freeze
2
+ VERSION = '2.2.0'.freeze
3
3
  end
@@ -36,5 +36,14 @@ module Hyperclient
36
36
  it 'is a collection' do
37
37
  _(Attributes.ancestors).must_include Collection
38
38
  end
39
+
40
+ describe 'when the representation is not a Hash' do
41
+ it 'wraps the representation as-is instead of filtering reserved keys' do
42
+ representation = 'not a hash'
43
+ attributes = Attributes.new(representation)
44
+
45
+ _(attributes.instance_variable_get(:@collection)).must_equal representation
46
+ end
47
+ end
39
48
  end
40
49
  end
@@ -41,6 +41,28 @@ module Hyperclient
41
41
  end
42
42
  end
43
43
 
44
+ describe '#to_h' do
45
+ it 'returns the wrapped collection as a hash' do
46
+ _(collection.to_h).must_be_kind_of Hash
47
+ end
48
+
49
+ it 'returns the same result as #to_hash' do
50
+ _(collection.to_h).must_equal(collection.to_hash)
51
+ end
52
+ end
53
+
54
+ describe '#to_s' do
55
+ it 'returns the wrapped collection as a hash' do
56
+ _(collection.to_s).must_be_kind_of Hash
57
+ end
58
+ end
59
+
60
+ describe '#method_missing' do
61
+ it 'raises an error for missing keys' do
62
+ _(proc { collection.missing_key }).must_raise RuntimeError
63
+ end
64
+ end
65
+
44
66
  describe 'include?' do
45
67
  it 'returns true for keys that exist' do
46
68
  _(collection.include?('_links')).must_equal true
@@ -34,5 +34,12 @@ module Hyperclient
34
34
  _(curie.expand('thumbnail')).must_equal '/images/thumbnail'
35
35
  end
36
36
  end
37
+
38
+ describe 'inspect' do
39
+ it 'outputs a custom-friendly output' do
40
+ _(curie.inspect).must_include 'Curie'
41
+ _(curie.inspect).must_include({ 'name' => 'image', 'href' => '/images/{rel}', 'templated' => true }.to_s)
42
+ end
43
+ end
37
44
  end
38
45
  end
@@ -21,6 +21,7 @@ module Hyperclient
21
21
  it 'can update headers after a connection has been constructed' do
22
22
  _(entry_point.connection).must_be_kind_of Faraday::Connection
23
23
  entry_point.headers.update('Content-Type' => 'application/foobar')
24
+
24
25
  _(entry_point.headers['Content-Type']).must_equal 'application/foobar'
25
26
  end
26
27
 
@@ -28,6 +29,7 @@ module Hyperclient
28
29
  _(entry_point.connection).must_be_kind_of Faraday::Connection
29
30
  entry_point.connection.use Faraday::Request::Instrumentation
30
31
  handlers = entry_point.connection.builder.handlers
32
+
31
33
  _(handlers).must_include Faraday::Request::Instrumentation
32
34
  end
33
35
 
@@ -51,6 +53,19 @@ module Hyperclient
51
53
  _(entry_point.connection).must_be_kind_of Faraday::Connection
52
54
  _(-> { entry_point.connection {} }).must_raise ConnectionAlreadyInitializedError
53
55
  end
56
+
57
+ it 'can set the faraday block before a connection has been constructed' do
58
+ block = proc { |conn| conn.use Faraday::Request::Instrumentation }
59
+ entry_point.faraday_block = block
60
+
61
+ _(entry_point.faraday_block).must_equal block
62
+ end
63
+
64
+ it 'raises a ConnectionAlreadyInitializedError if attempting to modify ' \
65
+ 'the faraday block after a connection has been constructed' do
66
+ _(entry_point.connection).must_be_kind_of Faraday::Connection
67
+ _(-> { entry_point.faraday_block = proc {} }).must_raise ConnectionAlreadyInitializedError
68
+ end
54
69
  end
55
70
 
56
71
  describe 'initialize' do
@@ -108,6 +123,20 @@ module Hyperclient
108
123
  end
109
124
  end
110
125
 
126
+ describe 'enforce_allowed_methods' do
127
+ it 'is disabled by default' do
128
+ _(EntryPoint.new('http://my.api.org').enforce_allowed_methods?).must_equal false
129
+ end
130
+
131
+ it 'can be enabled in the block' do
132
+ entry_point = EntryPoint.new('http://my.api.org') do |client|
133
+ client.enforce_allowed_methods = true
134
+ end
135
+
136
+ _(entry_point.enforce_allowed_methods?).must_equal true
137
+ end
138
+ end
139
+
111
140
  describe 'custom' do
112
141
  let(:entry_point) do
113
142
  EntryPoint.new 'http://my.api.org' do |entry_point|
@@ -136,6 +165,7 @@ module Hyperclient
136
165
 
137
166
  it 'creates a Faraday connection with the default block' do
138
167
  handlers = entry_point.connection.builder.handlers
168
+
139
169
  _(handlers).wont_include Faraday::Response::RaiseError
140
170
  _(handlers).wont_include Faraday::FollowRedirects
141
171
  _(handlers).must_include Faraday::Request::Json
@@ -178,5 +208,11 @@ module Hyperclient
178
208
  end
179
209
  end
180
210
  end
211
+
212
+ describe ConnectionAlreadyInitializedError do
213
+ it 'has a descriptive message' do
214
+ _(ConnectionAlreadyInitializedError.new.message).must_equal 'The connection has already been initialized.'
215
+ end
216
+ end
181
217
  end
182
218
  end
@@ -32,6 +32,7 @@ module Hyperclient
32
32
 
33
33
  describe 'plain link' do
34
34
  let(:plain_link) { links.self }
35
+
35
36
  it 'must be correct' do
36
37
  _(plain_link._url).must_equal '/productions/1'
37
38
  end
@@ -39,6 +40,7 @@ module Hyperclient
39
40
 
40
41
  describe 'templated link' do
41
42
  let(:templated_link) { links.search }
43
+
42
44
  it 'must expand' do
43
45
  _(templated_link._expand(search: 'gizmos')._url).must_equal '/productions/1?categories=gizmos'
44
46
  end
@@ -47,6 +49,7 @@ module Hyperclient
47
49
  describe 'curied link collection' do
48
50
  let(:curied_link) { links['image:thumbnail'] }
49
51
  let(:curie) { links._curies['image'] }
52
+
50
53
  it 'must expand' do
51
54
  _(curied_link._expand(version: 'small')._url).must_equal '/images/thumbnails/small.jpg'
52
55
  end
@@ -71,9 +74,16 @@ module Hyperclient
71
74
 
72
75
  describe 'null link value' do
73
76
  let(:null_link) { links.null_link }
77
+
74
78
  it 'must be nil' do
75
79
  _(null_link).must_be_nil
76
80
  end
77
81
  end
82
+
83
+ describe 'invalid collection' do
84
+ it 'raises an error when the collection does not respond to collect' do
85
+ _(proc { LinkCollection.new('invalid', {}, entry_point) }).must_raise RuntimeError
86
+ end
87
+ end
78
88
  end
79
89
  end