leal 0.0.9

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.
Files changed (127) hide show
  1. checksums.yaml +7 -0
  2. data/.fern/metadata.json +10 -0
  3. data/.fernignore +1 -0
  4. data/.rubocop.yml +103 -0
  5. data/CONTRIBUTING.md +120 -0
  6. data/LICENSE +21 -0
  7. data/README.md +185 -0
  8. data/Rakefile +20 -0
  9. data/custom.gemspec.rb +16 -0
  10. data/lib/leal/cards/client.rb +193 -0
  11. data/lib/leal/cards/types/create_cards_request.rb +13 -0
  12. data/lib/leal/cards/types/create_cards_request_card.rb +33 -0
  13. data/lib/leal/cards/types/create_cards_response.rb +45 -0
  14. data/lib/leal/cards/types/get_cards_request.rb +13 -0
  15. data/lib/leal/cards/types/get_cards_response.rb +45 -0
  16. data/lib/leal/cards/types/list_cards_request.rb +13 -0
  17. data/lib/leal/cards/types/list_cards_response_item.rb +45 -0
  18. data/lib/leal/cards/types/update_cards_request.rb +15 -0
  19. data/lib/leal/cards/types/update_cards_request_card.rb +33 -0
  20. data/lib/leal/cards/types/update_cards_response.rb +45 -0
  21. data/lib/leal/client.rb +62 -0
  22. data/lib/leal/customer_cards/client.rb +203 -0
  23. data/lib/leal/customer_cards/types/get_customer_cards_request.rb +15 -0
  24. data/lib/leal/customer_cards/types/get_customer_cards_response.rb +43 -0
  25. data/lib/leal/customer_cards/types/list_customer_cards_request.rb +13 -0
  26. data/lib/leal/customer_cards/types/list_customer_cards_response_item.rb +37 -0
  27. data/lib/leal/customer_cards/types/redeem_customer_cards_request.rb +17 -0
  28. data/lib/leal/customer_cards/types/redeem_customer_cards_response.rb +13 -0
  29. data/lib/leal/customer_cards/types/redeem_customer_cards_response_redemption.rb +21 -0
  30. data/lib/leal/customer_cards/types/stamp_customer_cards_request.rb +19 -0
  31. data/lib/leal/customer_cards/types/stamp_customer_cards_response.rb +43 -0
  32. data/lib/leal/customers/client.rb +217 -0
  33. data/lib/leal/customers/types/create_customers_request.rb +17 -0
  34. data/lib/leal/customers/types/create_customers_request_customer.rb +23 -0
  35. data/lib/leal/customers/types/create_customers_response.rb +35 -0
  36. data/lib/leal/customers/types/get_customers_request.rb +13 -0
  37. data/lib/leal/customers/types/get_customers_response.rb +35 -0
  38. data/lib/leal/customers/types/list_customers_request.rb +21 -0
  39. data/lib/leal/customers/types/list_customers_response.rb +13 -0
  40. data/lib/leal/customers/types/list_customers_response_pagination.rb +17 -0
  41. data/lib/leal/customers/types/update_customers_request.rb +15 -0
  42. data/lib/leal/customers/types/update_customers_request_customer.rb +23 -0
  43. data/lib/leal/customers/types/update_customers_response.rb +35 -0
  44. data/lib/leal/environment.rb +7 -0
  45. data/lib/leal/errors/api_error.rb +8 -0
  46. data/lib/leal/errors/client_error.rb +17 -0
  47. data/lib/leal/errors/redirect_error.rb +8 -0
  48. data/lib/leal/errors/response_error.rb +42 -0
  49. data/lib/leal/errors/server_error.rb +11 -0
  50. data/lib/leal/errors/timeout_error.rb +8 -0
  51. data/lib/leal/internal/errors/constraint_error.rb +10 -0
  52. data/lib/leal/internal/errors/type_error.rb +10 -0
  53. data/lib/leal/internal/http/base_request.rb +51 -0
  54. data/lib/leal/internal/http/raw_client.rb +265 -0
  55. data/lib/leal/internal/iterators/cursor_item_iterator.rb +28 -0
  56. data/lib/leal/internal/iterators/cursor_page_iterator.rb +63 -0
  57. data/lib/leal/internal/iterators/item_iterator.rb +65 -0
  58. data/lib/leal/internal/iterators/offset_item_iterator.rb +30 -0
  59. data/lib/leal/internal/iterators/offset_page_iterator.rb +103 -0
  60. data/lib/leal/internal/json/request.rb +41 -0
  61. data/lib/leal/internal/json/serializable.rb +25 -0
  62. data/lib/leal/internal/multipart/multipart_encoder.rb +141 -0
  63. data/lib/leal/internal/multipart/multipart_form_data.rb +78 -0
  64. data/lib/leal/internal/multipart/multipart_form_data_part.rb +51 -0
  65. data/lib/leal/internal/multipart/multipart_request.rb +40 -0
  66. data/lib/leal/internal/types/array.rb +47 -0
  67. data/lib/leal/internal/types/boolean.rb +34 -0
  68. data/lib/leal/internal/types/enum.rb +56 -0
  69. data/lib/leal/internal/types/hash.rb +36 -0
  70. data/lib/leal/internal/types/model/field.rb +38 -0
  71. data/lib/leal/internal/types/model.rb +208 -0
  72. data/lib/leal/internal/types/type.rb +35 -0
  73. data/lib/leal/internal/types/union.rb +161 -0
  74. data/lib/leal/internal/types/unknown.rb +15 -0
  75. data/lib/leal/internal/types/utils.rb +116 -0
  76. data/lib/leal/locations/client.rb +225 -0
  77. data/lib/leal/locations/types/create_locations_request.rb +13 -0
  78. data/lib/leal/locations/types/create_locations_request_location.rb +13 -0
  79. data/lib/leal/locations/types/create_locations_response.rb +25 -0
  80. data/lib/leal/locations/types/delete_locations_request.rb +13 -0
  81. data/lib/leal/locations/types/get_locations_request.rb +13 -0
  82. data/lib/leal/locations/types/get_locations_response.rb +25 -0
  83. data/lib/leal/locations/types/list_locations_request.rb +11 -0
  84. data/lib/leal/locations/types/list_locations_response_item.rb +25 -0
  85. data/lib/leal/locations/types/update_locations_request.rb +15 -0
  86. data/lib/leal/locations/types/update_locations_request_location.rb +13 -0
  87. data/lib/leal/locations/types/update_locations_response.rb +25 -0
  88. data/lib/leal/posters/client.rb +232 -0
  89. data/lib/leal/posters/types/create_posters_request.rb +13 -0
  90. data/lib/leal/posters/types/create_posters_request_poster.rb +23 -0
  91. data/lib/leal/posters/types/create_posters_response.rb +37 -0
  92. data/lib/leal/posters/types/delete_posters_request.rb +13 -0
  93. data/lib/leal/posters/types/get_posters_request.rb +13 -0
  94. data/lib/leal/posters/types/get_posters_response.rb +37 -0
  95. data/lib/leal/posters/types/list_posters_request.rb +15 -0
  96. data/lib/leal/posters/types/list_posters_response_item.rb +37 -0
  97. data/lib/leal/posters/types/update_posters_request.rb +15 -0
  98. data/lib/leal/posters/types/update_posters_request_poster.rb +21 -0
  99. data/lib/leal/posters/types/update_posters_response.rb +37 -0
  100. data/lib/leal/rewards/client.rb +233 -0
  101. data/lib/leal/rewards/types/create_rewards_request.rb +13 -0
  102. data/lib/leal/rewards/types/create_rewards_request_reward.rb +21 -0
  103. data/lib/leal/rewards/types/create_rewards_response.rb +29 -0
  104. data/lib/leal/rewards/types/delete_rewards_request.rb +13 -0
  105. data/lib/leal/rewards/types/get_rewards_request.rb +13 -0
  106. data/lib/leal/rewards/types/get_rewards_response.rb +29 -0
  107. data/lib/leal/rewards/types/list_rewards_request.rb +15 -0
  108. data/lib/leal/rewards/types/list_rewards_response_item.rb +29 -0
  109. data/lib/leal/rewards/types/update_rewards_request.rb +15 -0
  110. data/lib/leal/rewards/types/update_rewards_request_reward.rb +19 -0
  111. data/lib/leal/rewards/types/update_rewards_response.rb +29 -0
  112. data/lib/leal/status/client.rb +53 -0
  113. data/lib/leal/status/types/check_status_response.rb +23 -0
  114. data/lib/leal/status/types/check_status_response_rate_limit.rb +15 -0
  115. data/lib/leal/stores/client.rb +130 -0
  116. data/lib/leal/stores/types/get_stores_request.rb +11 -0
  117. data/lib/leal/stores/types/get_stores_response.rb +31 -0
  118. data/lib/leal/stores/types/list_stores_response_item.rb +31 -0
  119. data/lib/leal/stores/types/update_stores_request.rb +13 -0
  120. data/lib/leal/stores/types/update_stores_request_account.rb +13 -0
  121. data/lib/leal/stores/types/update_stores_response.rb +31 -0
  122. data/lib/leal/types/error.rb +13 -0
  123. data/lib/leal/types/error_errors.rb +14 -0
  124. data/lib/leal/version.rb +5 -0
  125. data/lib/leal.rb +120 -0
  126. data/reference.md +2414 -0
  127. metadata +168 -0
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Errors
5
+ class ResponseError < ApiError
6
+ attr_reader :code
7
+
8
+ def initialize(msg, code:)
9
+ @code = code
10
+ super(msg)
11
+ end
12
+
13
+ def inspect
14
+ "#<#{self.class.name} @code=#{code} @body=#{message}>"
15
+ end
16
+
17
+ # Returns the most appropriate error class for the given code.
18
+ #
19
+ # @return [Class]
20
+ def self.subclass_for_code(code)
21
+ case code
22
+ when 300..399
23
+ RedirectError
24
+ when 401
25
+ UnauthorizedError
26
+ when 403
27
+ ForbiddenError
28
+ when 404
29
+ NotFoundError
30
+ when 400..499
31
+ ClientError
32
+ when 503
33
+ ServiceUnavailableError
34
+ when 500..599
35
+ ServerError
36
+ else
37
+ ResponseError
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Errors
5
+ class ServerError < ResponseError
6
+ end
7
+
8
+ class ServiceUnavailableError < ApiError
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Errors
5
+ class TimeoutError < ApiError
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ module Errors
6
+ class ConstraintError < StandardError
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ module Errors
6
+ class TypeError < StandardError
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ module Http
6
+ # @api private
7
+ class BaseRequest
8
+ attr_reader :base_url, :path, :method, :headers, :query, :request_options
9
+
10
+ # @param base_url [String] The base URL for the request
11
+ # @param path [String] The path for the request
12
+ # @param method [String] The HTTP method for the request (:get, :post, etc.)
13
+ # @param headers [Hash] Additional headers for the request (optional)
14
+ # @param query [Hash] Query parameters for the request (optional)
15
+ # @param request_options [Leal::RequestOptions, Hash{Symbol=>Object}, nil]
16
+ def initialize(base_url:, path:, method:, headers: {}, query: {}, request_options: {})
17
+ @base_url = base_url
18
+ @path = path
19
+ @method = method
20
+ @headers = headers
21
+ @query = query
22
+ @request_options = request_options
23
+ end
24
+
25
+ # @return [Hash] The query parameters merged with additional query parameters from request options.
26
+ def encode_query
27
+ additional_query = @request_options&.dig(:additional_query_parameters) || @request_options&.dig("additional_query_parameters") || {}
28
+ @query.merge(additional_query)
29
+ end
30
+
31
+ # Child classes should implement:
32
+ # - encode_headers: Returns the encoded HTTP request headers.
33
+ # - encode_body: Returns the encoded HTTP request body.
34
+
35
+ private
36
+
37
+ # Merges additional_headers from request_options into sdk_headers, filtering out
38
+ # any keys that collide with SDK-set or client-protected headers (case-insensitive).
39
+ # @param sdk_headers [Hash] Headers set by the SDK for this request type.
40
+ # @param protected_keys [Array<String>] Additional header keys that must not be overridden.
41
+ # @return [Hash] The merged headers.
42
+ def merge_additional_headers(sdk_headers, protected_keys: [])
43
+ additional_headers = @request_options&.dig(:additional_headers) || @request_options&.dig("additional_headers") || {}
44
+ all_protected = (sdk_headers.keys + protected_keys).to_set { |k| k.to_s.downcase }
45
+ filtered = additional_headers.reject { |key, _| all_protected.include?(key.to_s.downcase) }
46
+ sdk_headers.merge(filtered)
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,265 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ module Http
6
+ # @api private
7
+ class RawClient
8
+ # Default HTTP status codes that trigger a retry
9
+ RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504, 521, 522, 524].freeze
10
+ # Initial delay between retries in seconds
11
+ INITIAL_RETRY_DELAY = 0.5
12
+ # Maximum delay between retries in seconds
13
+ MAX_RETRY_DELAY = 60.0
14
+ # Jitter factor for randomizing retry delays (20%)
15
+ JITTER_FACTOR = 0.2
16
+
17
+ # @return [String] The base URL for requests
18
+ attr_reader :base_url
19
+
20
+ # @param base_url [String] The base url for the request.
21
+ # @param max_retries [Integer] The number of times to retry a failed request, defaults to 2.
22
+ # @param timeout [Float] The timeout for the request, defaults to 60.0 seconds.
23
+ # @param headers [Hash] The headers for the request.
24
+ # @param overridable_headers [Array<String>] The names of the client-level headers a request
25
+ # may replace via `additional_headers`. Holds the API's global headers; SDK metadata and
26
+ # auth headers are absent from it and so stay protected.
27
+ # @param auth_provider [Object, nil] An optional auth provider responding to
28
+ # `auth_headers`. When present its headers are resolved on every request so
29
+ # token-based schemes (e.g. OAuth) can refresh an expired token mid-session.
30
+ def initialize(base_url:, max_retries: 2, timeout: 60.0, headers: {}, overridable_headers: [], auth_provider: nil)
31
+ @base_url = base_url
32
+ @max_retries = max_retries
33
+ @timeout = timeout
34
+ @auth_provider = auth_provider
35
+ @default_headers = {
36
+ "X-Fern-Language": "Ruby",
37
+ "X-Fern-SDK-Name": "leal",
38
+ "X-Fern-SDK-Version": "0.0.1"
39
+ }.merge(headers)
40
+ @overridable_headers = overridable_headers.to_set { |name| name.to_s.downcase }
41
+ end
42
+
43
+ # @param request [Leal::Internal::Http::BaseRequest] The HTTP request.
44
+ # @return [HTTP::Response] The HTTP response.
45
+ def send(request)
46
+ url = build_url(request)
47
+ # Resolve auth headers once per request (not per retry) so token-based
48
+ # providers refresh at most once here; static providers are cheap.
49
+ auth_headers = resolve_auth_headers
50
+ attempt = 0
51
+ response = nil
52
+
53
+ loop do
54
+ http_request = build_http_request(
55
+ url:,
56
+ method: request.method,
57
+ headers: request.encode_headers(protected_keys: protected_header_keys + auth_headers.keys),
58
+ body: request.encode_body,
59
+ auth_headers: auth_headers
60
+ )
61
+
62
+ conn = connect(url)
63
+ conn.open_timeout = @timeout
64
+ conn.read_timeout = @timeout
65
+ conn.write_timeout = @timeout
66
+ conn.continue_timeout = @timeout
67
+
68
+ response = conn.request(http_request)
69
+
70
+ break unless should_retry?(response, attempt)
71
+
72
+ delay = retry_delay(response, attempt)
73
+ sleep(delay)
74
+ attempt += 1
75
+ end
76
+
77
+ response
78
+ end
79
+
80
+ # The client-level header names that `additional_headers` must not replace: every default
81
+ # header except the API's global headers, which are overridable per request.
82
+ # @return [Array<Symbol, String>] The protected header names.
83
+ def protected_header_keys
84
+ return @default_headers.keys if @overridable_headers.empty?
85
+
86
+ @default_headers.keys.reject { |name| @overridable_headers.include?(name.to_s.downcase) }
87
+ end
88
+
89
+ # Determines if a request should be retried based on the response status code.
90
+ # @param response [Net::HTTPResponse] The HTTP response.
91
+ # @param attempt [Integer] The current retry attempt (0-indexed).
92
+ # @return [Boolean] Whether the request should be retried.
93
+ def should_retry?(response, attempt)
94
+ return false if attempt >= @max_retries
95
+
96
+ status = response.code.to_i
97
+ RETRYABLE_STATUSES.include?(status)
98
+ end
99
+
100
+ # Calculates the delay before the next retry attempt using exponential backoff with jitter.
101
+ # Respects Retry-After header if present.
102
+ # @param response [Net::HTTPResponse] The HTTP response.
103
+ # @param attempt [Integer] The current retry attempt (0-indexed).
104
+ # @return [Float] The delay in seconds before the next retry.
105
+ def retry_delay(response, attempt)
106
+ # Check for Retry-After header (can be seconds or HTTP date)
107
+ retry_after = response["Retry-After"]
108
+ if retry_after
109
+ delay = parse_retry_after(retry_after)
110
+ return [delay, MAX_RETRY_DELAY].min if delay&.positive?
111
+ end
112
+
113
+ # Exponential backoff with jitter: base_delay * 2^attempt
114
+ base_delay = INITIAL_RETRY_DELAY * (2**attempt)
115
+ add_jitter([base_delay, MAX_RETRY_DELAY].min)
116
+ end
117
+
118
+ # Parses the Retry-After header value.
119
+ # @param value [String] The Retry-After header value (seconds or HTTP date).
120
+ # @return [Float, nil] The delay in seconds, or nil if parsing fails.
121
+ def parse_retry_after(value)
122
+ # Try parsing as integer (seconds)
123
+ seconds = Integer(value, exception: false)
124
+ return seconds.to_f if seconds
125
+
126
+ # Try parsing as HTTP date
127
+ begin
128
+ retry_time = Time.httpdate(value)
129
+ delay = retry_time - Time.now
130
+ delay.positive? ? delay : nil
131
+ rescue ArgumentError
132
+ nil
133
+ end
134
+ end
135
+
136
+ # Adds random jitter to a delay value.
137
+ # @param delay [Float] The base delay in seconds.
138
+ # @return [Float] The delay with jitter applied.
139
+ def add_jitter(delay)
140
+ jitter = delay * JITTER_FACTOR * (rand - 0.5) * 2
141
+ [delay + jitter, 0].max
142
+ end
143
+
144
+ LOCALHOST_HOSTS = %w[localhost 127.0.0.1 [::1]].freeze
145
+
146
+ # @param request [Leal::Internal::Http::BaseRequest] The HTTP request.
147
+ # @return [URI::Generic] The URL.
148
+ def build_url(request)
149
+ encoded_query = request.encode_query
150
+
151
+ # If the path is already an absolute URL, use it directly
152
+ if request.path.start_with?("http://", "https://")
153
+ url = request.path
154
+ url = "#{url}?#{encode_query(encoded_query)}" if encoded_query&.any?
155
+ parsed = URI.parse(url)
156
+ validate_https!(parsed)
157
+ return parsed
158
+ end
159
+
160
+ path = request.path.start_with?("/") ? request.path[1..] : request.path
161
+ base = request.base_url || @base_url
162
+ url = "#{base.chomp("/")}/#{path}"
163
+ url = "#{url}?#{encode_query(encoded_query)}" if encoded_query&.any?
164
+ parsed = URI.parse(url)
165
+ validate_https!(parsed)
166
+ parsed
167
+ end
168
+
169
+ # Raises if the URL uses http:// for a non-localhost host, which would
170
+ # send authentication credentials in plaintext.
171
+ # @param url [URI::Generic] The parsed URL.
172
+ def validate_https!(url)
173
+ return if url.scheme != "http"
174
+ return if LOCALHOST_HOSTS.include?(url.host)
175
+
176
+ raise ArgumentError,
177
+ "Refusing to send request to non-HTTPS URL: #{url}. " \
178
+ "HTTP is only allowed for localhost. Use HTTPS or pass a localhost URL."
179
+ end
180
+
181
+ # Resolves the auth headers to send with the next request. Delegates to the
182
+ # configured auth provider (if any) on every call so that token-based
183
+ # providers (e.g. OAuth client-credentials) can refresh an expired token
184
+ # before the request is sent. Returns an empty hash when no provider is set,
185
+ # which keeps the api-key / basic / bearer / no-auth paths unchanged.
186
+ # @return [Hash] The auth headers for the current request.
187
+ def resolve_auth_headers
188
+ return {} if @auth_provider.nil?
189
+
190
+ @auth_provider.auth_headers
191
+ end
192
+
193
+ # @param url [URI::Generic] The url to the resource.
194
+ # @param method [String] The HTTP method to use.
195
+ # @param headers [Hash] The headers for the request.
196
+ # @param body [String, nil] The body for the request.
197
+ # @param auth_headers [Hash] The auth headers resolved for this request. These
198
+ # take precedence over the static default headers but not over per-request
199
+ # headers, mirroring the previous baked-header precedence.
200
+ # @return [HTTP::Request] The HTTP request.
201
+ def build_http_request(url:, method:, headers: {}, body: nil, auth_headers: {})
202
+ request = Net::HTTPGenericRequest.new(
203
+ method,
204
+ !body.nil?,
205
+ method != "HEAD",
206
+ url
207
+ )
208
+
209
+ request_headers = @default_headers.merge(auth_headers).merge(headers)
210
+ request_headers.each { |name, value| request[name] = value }
211
+ request.body = body if body
212
+
213
+ # Net::HTTP disables its transparent gzip/deflate decoding as soon as an
214
+ # Accept-Encoding header is set explicitly on the request. Re-enable it so
215
+ # that compressed response bodies are still inflated.
216
+ request.extend(DecodeContent) if request_headers.keys.any? { |name| name.to_s.casecmp("accept-encoding").zero? }
217
+
218
+ request
219
+ end
220
+
221
+ # Keeps Net::HTTP's transparent gzip/deflate response decoding enabled
222
+ # even when an Accept-Encoding header is set explicitly on the request.
223
+ # @api private
224
+ module DecodeContent
225
+ def decode_content # rubocop:disable Naming/PredicateMethod
226
+ true
227
+ end
228
+ end
229
+
230
+ # @param query [Hash] The query for the request.
231
+ # @return [String, nil] The encoded query.
232
+ def encode_query(query)
233
+ query.to_h.empty? ? nil : URI.encode_www_form(query)
234
+ end
235
+
236
+ # @param url [URI::Generic] The url to connect to.
237
+ # @return [Net::HTTP] The HTTP connection.
238
+ def connect(url)
239
+ is_https = (url.scheme == "https")
240
+
241
+ port = if url.port
242
+ url.port
243
+ elsif is_https
244
+ Net::HTTP.https_default_port
245
+ else
246
+ Net::HTTP.http_default_port
247
+ end
248
+
249
+ http = Net::HTTP.new(url.host, port)
250
+ http.use_ssl = is_https
251
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER if is_https
252
+ # NOTE: We handle retries at the application level with HTTP status code awareness,
253
+ # so we set max_retries to 0 to disable Net::HTTP's built-in network-level retries.
254
+ http.max_retries = 0
255
+ http
256
+ end
257
+
258
+ # @return [String]
259
+ def inspect
260
+ "#<#{self.class.name}:0x#{object_id.to_s(16)} @base_url=#{@base_url.inspect}>"
261
+ end
262
+ end
263
+ end
264
+ end
265
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ class CursorItemIterator < ItemIterator
6
+ # Instantiates a CursorItemIterator, an Enumerable class which wraps calls to a cursor-based paginated API and yields individual items from it.
7
+ #
8
+ # @param initial_cursor [String] The initial cursor to use when iterating, if any.
9
+ # @param cursor_field [Symbol] The field in API responses to extract the next cursor from.
10
+ # @param item_field [Symbol] The field in API responses to extract the items to iterate over.
11
+ # @param block [Proc] A block which is responsible for receiving a cursor to use and returning the given page from the API.
12
+ # @return [Leal::Internal::CursorItemIterator]
13
+ def initialize(initial_cursor:, cursor_field:, item_field:, &)
14
+ super()
15
+ @item_field = item_field
16
+ @page_iterator = CursorPageIterator.new(initial_cursor:, cursor_field:, &)
17
+ @page = nil
18
+ end
19
+
20
+ # Returns the CursorPageIterator mediating access to the underlying API.
21
+ #
22
+ # @return [Leal::Internal::CursorPageIterator]
23
+ def pages
24
+ @page_iterator
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ class CursorPageIterator
6
+ include Enumerable
7
+
8
+ # The raw HTTP response from the most recent page response.
9
+ # @return [Net::HTTPResponse, nil]
10
+ attr_reader :http_response
11
+
12
+ # Instantiates a CursorPageIterator, an Enumerable class which wraps calls to a cursor-based paginated API and yields pages of items.
13
+ #
14
+ # @param initial_cursor [String] The initial cursor to use when iterating, if any.
15
+ # @param cursor_field [Symbol] The name of the field in API responses to extract the next cursor from.
16
+ # @param block [Proc] A block which is responsible for receiving a cursor to use and returning the given page from the API.
17
+ # The block should return a two-element array: [parsed_page, raw_http_response].
18
+ # @return [Leal::Internal::CursorPageIterator]
19
+ def initialize(initial_cursor:, cursor_field:, &block)
20
+ @need_initial_load = initial_cursor.nil?
21
+ @cursor = initial_cursor
22
+ @cursor_field = cursor_field
23
+ @get_next_page = block
24
+ @http_response = nil
25
+ end
26
+
27
+ # Iterates over each page returned by the API.
28
+ #
29
+ # @param block [Proc] The block which each retrieved page is yielded to.
30
+ # @return [NilClass]
31
+ def each(&block)
32
+ while (page = next_page)
33
+ block.call(page)
34
+ end
35
+ end
36
+
37
+ # Whether another page will be available from the API.
38
+ #
39
+ # @return [Boolean]
40
+ def next?
41
+ @need_initial_load || !@cursor.nil?
42
+ end
43
+
44
+ # Retrieves the next page from the API.
45
+ #
46
+ # @return [Object, nil]
47
+ def next_page
48
+ return if !@need_initial_load && @cursor.nil?
49
+
50
+ @need_initial_load = false
51
+ result = @get_next_page.call(@cursor)
52
+ if result.is_a?(Array)
53
+ fetched_page, raw_response = result
54
+ @http_response = raw_response
55
+ else
56
+ fetched_page = result
57
+ end
58
+ @cursor = fetched_page.send(@cursor_field)
59
+ fetched_page
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ class ItemIterator
6
+ include Enumerable
7
+
8
+ # The raw HTTP response from the most recent page response.
9
+ # @return [Net::HTTPResponse, nil]
10
+ def http_response
11
+ @page_iterator&.http_response
12
+ end
13
+
14
+ # Iterates over each item returned by the API.
15
+ #
16
+ # @param block [Proc] The block which each retrieved item is yielded to.
17
+ # @return [NilClass]
18
+ def each(&block)
19
+ while (item = next_element)
20
+ block.call(item)
21
+ end
22
+ end
23
+
24
+ # Whether another item will be available from the API.
25
+ #
26
+ # @return [Boolean]
27
+ def next?
28
+ load_next_page if @page.nil?
29
+ return false if @page.nil?
30
+
31
+ return true if any_items_in_cached_page?
32
+
33
+ load_next_page
34
+ any_items_in_cached_page?
35
+ end
36
+
37
+ # Retrieves the next item from the API.
38
+ def next_element
39
+ item = next_item_from_cached_page
40
+ return item if item
41
+
42
+ load_next_page
43
+ next_item_from_cached_page
44
+ end
45
+
46
+ private
47
+
48
+ def next_item_from_cached_page
49
+ return unless @page
50
+
51
+ @page.send(@item_field).shift
52
+ end
53
+
54
+ def any_items_in_cached_page?
55
+ return false unless @page
56
+
57
+ !@page.send(@item_field).empty?
58
+ end
59
+
60
+ def load_next_page
61
+ @page = @page_iterator.next_page
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leal
4
+ module Internal
5
+ class OffsetItemIterator < ItemIterator
6
+ # Instantiates an OffsetItemIterator, an Enumerable class which wraps calls to an offset-based paginated API and yields the individual items from it.
7
+ #
8
+ # @param initial_page [Integer] The initial page or offset to start from when iterating.
9
+ # @param item_field [Symbol] The name of the field in API responses to extract the items to iterate over.
10
+ # @param has_next_field [Symbol] The name of the field in API responses containing a boolean of whether another page exists.
11
+ # @param step [Boolean] If true, treats the page number as a true offset (i.e. increments the page number by the number of items returned from each call rather than just 1)
12
+ # @param block [Proc] A block which is responsible for receiving a page number to use and returning the given page from the API.
13
+ #
14
+ # @return [Leal::Internal::OffsetItemIterator]
15
+ def initialize(initial_page:, item_field:, has_next_field:, step:, &)
16
+ super()
17
+ @item_field = item_field
18
+ @page_iterator = OffsetPageIterator.new(initial_page:, item_field:, has_next_field:, step:, &)
19
+ @page = nil
20
+ end
21
+
22
+ # Returns the OffsetPageIterator that is mediating access to the underlying API.
23
+ #
24
+ # @return [Leal::Internal::OffsetPageIterator]
25
+ def pages
26
+ @page_iterator
27
+ end
28
+ end
29
+ end
30
+ end