pokeapi_client 0.9.0 → 0.9.1

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 (109) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile.lock +1 -1
  3. data/README.md +5 -5
  4. data/lib/pokeapi_client/api/ability_api.rb +138 -0
  5. data/lib/pokeapi_client/api/berry_api.rb +138 -0
  6. data/lib/pokeapi_client/api/berry_firmness_api.rb +138 -0
  7. data/lib/pokeapi_client/api/berry_flavor_api.rb +138 -0
  8. data/lib/pokeapi_client/api/characteristic_api.rb +138 -0
  9. data/lib/pokeapi_client/api/contest_effect_api.rb +138 -0
  10. data/lib/pokeapi_client/api/contest_type_api.rb +138 -0
  11. data/lib/pokeapi_client/api/egg_group_api.rb +138 -0
  12. data/lib/pokeapi_client/api/encounter_condition_api.rb +138 -0
  13. data/lib/pokeapi_client/api/encounter_condition_value_api.rb +138 -0
  14. data/lib/pokeapi_client/api/encounter_method_api.rb +138 -0
  15. data/lib/pokeapi_client/api/evolution_chain_api.rb +138 -0
  16. data/lib/pokeapi_client/api/evolution_trigger_api.rb +138 -0
  17. data/lib/pokeapi_client/api/gender_api.rb +138 -0
  18. data/lib/pokeapi_client/api/generation_api.rb +138 -0
  19. data/lib/pokeapi_client/api/growth_rate_api.rb +138 -0
  20. data/lib/pokeapi_client/api/item_api.rb +138 -0
  21. data/lib/pokeapi_client/api/item_attribute_api.rb +138 -0
  22. data/lib/pokeapi_client/api/item_category_api.rb +138 -0
  23. data/lib/pokeapi_client/api/item_fling_effect_api.rb +138 -0
  24. data/lib/pokeapi_client/api/item_pocket_api.rb +138 -0
  25. data/lib/pokeapi_client/api/language_api.rb +138 -0
  26. data/lib/pokeapi_client/api/location_api.rb +138 -0
  27. data/lib/pokeapi_client/api/location_area_api.rb +138 -0
  28. data/lib/pokeapi_client/api/machine_api.rb +138 -0
  29. data/lib/pokeapi_client/api/move_ailment_api.rb +138 -0
  30. data/lib/pokeapi_client/api/move_api.rb +138 -0
  31. data/lib/pokeapi_client/api/move_battle_style_api.rb +138 -0
  32. data/lib/pokeapi_client/api/move_category_api.rb +138 -0
  33. data/lib/pokeapi_client/api/move_damage_class_api.rb +138 -0
  34. data/lib/pokeapi_client/api/move_learn_method_api.rb +138 -0
  35. data/lib/pokeapi_client/api/move_target_api.rb +138 -0
  36. data/lib/pokeapi_client/api/nature_api.rb +138 -0
  37. data/lib/pokeapi_client/api/pal_park_area_api.rb +138 -0
  38. data/lib/pokeapi_client/api/pokeathlon_stat_api.rb +138 -0
  39. data/lib/pokeapi_client/api/pokedex_api.rb +138 -0
  40. data/lib/pokeapi_client/api/pokemon_api.rb +138 -0
  41. data/lib/pokeapi_client/api/pokemon_color_api.rb +138 -0
  42. data/lib/pokeapi_client/api/pokemon_form_api.rb +138 -0
  43. data/lib/pokeapi_client/api/pokemon_habitat_api.rb +138 -0
  44. data/lib/pokeapi_client/api/pokemon_shape_api.rb +138 -0
  45. data/lib/pokeapi_client/api/pokemon_species_api.rb +138 -0
  46. data/lib/pokeapi_client/api/region_api.rb +138 -0
  47. data/lib/pokeapi_client/api/stat_api.rb +138 -0
  48. data/lib/pokeapi_client/api/super_contest_effect_api.rb +138 -0
  49. data/lib/pokeapi_client/api/type_api.rb +138 -0
  50. data/lib/pokeapi_client/api/version_api.rb +138 -0
  51. data/lib/pokeapi_client/api/version_group_api.rb +138 -0
  52. data/lib/pokeapi_client/api_client.rb +387 -0
  53. data/lib/pokeapi_client/api_error.rb +55 -0
  54. data/lib/pokeapi_client/configuration.rb +269 -0
  55. data/lib/pokeapi_client/version.rb +13 -0
  56. data/lib/pokeapi_client.rb +85 -0
  57. data/pokeapi_client.gemspec +3 -3
  58. data/spec/api/ability_api_spec.rb +4 -4
  59. data/spec/api/berry_api_spec.rb +4 -4
  60. data/spec/api/berry_firmness_api_spec.rb +4 -4
  61. data/spec/api/berry_flavor_api_spec.rb +4 -4
  62. data/spec/api/characteristic_api_spec.rb +4 -4
  63. data/spec/api/contest_effect_api_spec.rb +4 -4
  64. data/spec/api/contest_type_api_spec.rb +4 -4
  65. data/spec/api/egg_group_api_spec.rb +4 -4
  66. data/spec/api/encounter_condition_api_spec.rb +4 -4
  67. data/spec/api/encounter_condition_value_api_spec.rb +4 -4
  68. data/spec/api/encounter_method_api_spec.rb +4 -4
  69. data/spec/api/evolution_chain_api_spec.rb +4 -4
  70. data/spec/api/evolution_trigger_api_spec.rb +4 -4
  71. data/spec/api/gender_api_spec.rb +4 -4
  72. data/spec/api/generation_api_spec.rb +4 -4
  73. data/spec/api/growth_rate_api_spec.rb +4 -4
  74. data/spec/api/item_api_spec.rb +4 -4
  75. data/spec/api/item_attribute_api_spec.rb +4 -4
  76. data/spec/api/item_category_api_spec.rb +4 -4
  77. data/spec/api/item_fling_effect_api_spec.rb +4 -4
  78. data/spec/api/item_pocket_api_spec.rb +4 -4
  79. data/spec/api/language_api_spec.rb +4 -4
  80. data/spec/api/location_api_spec.rb +4 -4
  81. data/spec/api/location_area_api_spec.rb +4 -4
  82. data/spec/api/machine_api_spec.rb +4 -4
  83. data/spec/api/move_ailment_api_spec.rb +4 -4
  84. data/spec/api/move_api_spec.rb +4 -4
  85. data/spec/api/move_battle_style_api_spec.rb +4 -4
  86. data/spec/api/move_category_api_spec.rb +4 -4
  87. data/spec/api/move_damage_class_api_spec.rb +4 -4
  88. data/spec/api/move_learn_method_api_spec.rb +4 -4
  89. data/spec/api/move_target_api_spec.rb +4 -4
  90. data/spec/api/nature_api_spec.rb +4 -4
  91. data/spec/api/pal_park_area_api_spec.rb +4 -4
  92. data/spec/api/pokeathlon_stat_api_spec.rb +4 -4
  93. data/spec/api/pokedex_api_spec.rb +4 -4
  94. data/spec/api/pokemon_api_spec.rb +4 -4
  95. data/spec/api/pokemon_color_api_spec.rb +4 -4
  96. data/spec/api/pokemon_form_api_spec.rb +4 -4
  97. data/spec/api/pokemon_habitat_api_spec.rb +4 -4
  98. data/spec/api/pokemon_shape_api_spec.rb +4 -4
  99. data/spec/api/pokemon_species_api_spec.rb +4 -4
  100. data/spec/api/region_api_spec.rb +4 -4
  101. data/spec/api/stat_api_spec.rb +4 -4
  102. data/spec/api/super_contest_effect_api_spec.rb +4 -4
  103. data/spec/api/type_api_spec.rb +4 -4
  104. data/spec/api/version_api_spec.rb +4 -4
  105. data/spec/api/version_group_api_spec.rb +4 -4
  106. data/spec/api_client_spec.rb +1 -1
  107. data/spec/configuration_spec.rb +1 -1
  108. data/spec/spec_helper.rb +1 -1
  109. metadata +92 -39
@@ -0,0 +1,387 @@
1
+ =begin
2
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
3
+
4
+ The version of the OpenAPI document: 20220523
5
+
6
+ Generated by: https://openapi-generator.tech
7
+ OpenAPI Generator version: 5.4.0
8
+
9
+ =end
10
+
11
+ require 'date'
12
+ require 'json'
13
+ require 'logger'
14
+ require 'tempfile'
15
+ require 'time'
16
+ require 'typhoeus'
17
+
18
+ module PokeApiClient
19
+ class ApiClient
20
+ # The Configuration object holding settings to be used in the API client.
21
+ attr_accessor :config
22
+
23
+ # Defines the headers to be used in HTTP requests of all API calls by default.
24
+ #
25
+ # @return [Hash]
26
+ attr_accessor :default_headers
27
+
28
+ # Initializes the ApiClient
29
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
30
+ def initialize(config = Configuration.default)
31
+ @config = config
32
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
33
+ @default_headers = {
34
+ 'Content-Type' => 'application/json',
35
+ 'User-Agent' => @user_agent
36
+ }
37
+ end
38
+
39
+ def self.default
40
+ @@default ||= ApiClient.new
41
+ end
42
+
43
+ # Call an API with given options.
44
+ #
45
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
46
+ # the data deserialized from response body (could be nil), response status code and response headers.
47
+ def call_api(http_method, path, opts = {})
48
+ request = build_request(http_method, path, opts)
49
+ response = request.run
50
+
51
+ if @config.debugging
52
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
53
+ end
54
+
55
+ unless response.success?
56
+ if response.timed_out?
57
+ fail ApiError.new('Connection timed out')
58
+ elsif response.code == 0
59
+ # Errors from libcurl will be made visible here
60
+ fail ApiError.new(:code => 0,
61
+ :message => response.return_message)
62
+ else
63
+ fail ApiError.new(:code => response.code,
64
+ :response_headers => response.headers,
65
+ :response_body => response.body),
66
+ response.status_message
67
+ end
68
+ end
69
+
70
+ if opts[:return_type]
71
+ data = deserialize(response, opts[:return_type])
72
+ else
73
+ data = nil
74
+ end
75
+ return data, response.code, response.headers
76
+ end
77
+
78
+ # Builds the HTTP request
79
+ #
80
+ # @param [String] http_method HTTP method/verb (e.g. POST)
81
+ # @param [String] path URL path (e.g. /account/new)
82
+ # @option opts [Hash] :header_params Header parameters
83
+ # @option opts [Hash] :query_params Query parameters
84
+ # @option opts [Hash] :form_params Query parameters
85
+ # @option opts [Object] :body HTTP body (JSON/XML)
86
+ # @return [Typhoeus::Request] A Typhoeus Request
87
+ def build_request(http_method, path, opts = {})
88
+ url = build_request_url(path, opts)
89
+ http_method = http_method.to_sym.downcase
90
+
91
+ header_params = @default_headers.merge(opts[:header_params] || {})
92
+ query_params = opts[:query_params] || {}
93
+ form_params = opts[:form_params] || {}
94
+
95
+
96
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
97
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
98
+
99
+ req_opts = {
100
+ :method => http_method,
101
+ :headers => header_params,
102
+ :params => query_params,
103
+ :params_encoding => @config.params_encoding,
104
+ :timeout => @config.timeout,
105
+ :ssl_verifypeer => @config.verify_ssl,
106
+ :ssl_verifyhost => _verify_ssl_host,
107
+ :sslcert => @config.cert_file,
108
+ :sslkey => @config.key_file,
109
+ :verbose => @config.debugging
110
+ }
111
+
112
+ # set custom cert, if provided
113
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
114
+
115
+ if [:post, :patch, :put, :delete].include?(http_method)
116
+ req_body = build_request_body(header_params, form_params, opts[:body])
117
+ req_opts.update :body => req_body
118
+ if @config.debugging
119
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
120
+ end
121
+ end
122
+
123
+ request = Typhoeus::Request.new(url, req_opts)
124
+ download_file(request) if opts[:return_type] == 'File'
125
+ request
126
+ end
127
+
128
+ # Builds the HTTP request body
129
+ #
130
+ # @param [Hash] header_params Header parameters
131
+ # @param [Hash] form_params Query parameters
132
+ # @param [Object] body HTTP body (JSON/XML)
133
+ # @return [String] HTTP body data in the form of string
134
+ def build_request_body(header_params, form_params, body)
135
+ # http form
136
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
137
+ header_params['Content-Type'] == 'multipart/form-data'
138
+ data = {}
139
+ form_params.each do |key, value|
140
+ case value
141
+ when ::File, ::Array, nil
142
+ # let typhoeus handle File, Array and nil parameters
143
+ data[key] = value
144
+ else
145
+ data[key] = value.to_s
146
+ end
147
+ end
148
+ elsif body
149
+ data = body.is_a?(String) ? body : body.to_json
150
+ else
151
+ data = nil
152
+ end
153
+ data
154
+ end
155
+
156
+ # Save response body into a file in (the defined) temporary folder, using the filename
157
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
158
+ # The response body is written to the file in chunks in order to handle files which
159
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
160
+ # process can use.
161
+ #
162
+ # @see Configuration#temp_folder_path
163
+ def download_file(request)
164
+ tempfile = nil
165
+ encoding = nil
166
+ request.on_headers do |response|
167
+ content_disposition = response.headers['Content-Disposition']
168
+ if content_disposition && content_disposition =~ /filename=/i
169
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
170
+ prefix = sanitize_filename(filename)
171
+ else
172
+ prefix = 'download-'
173
+ end
174
+ prefix = prefix + '-' unless prefix.end_with?('-')
175
+ encoding = response.body.encoding
176
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
177
+ @tempfile = tempfile
178
+ end
179
+ request.on_body do |chunk|
180
+ chunk.force_encoding(encoding)
181
+ tempfile.write(chunk)
182
+ end
183
+ request.on_complete do |response|
184
+ if tempfile
185
+ tempfile.close
186
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
187
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
188
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
189
+ "explicitly with `tempfile.delete`"
190
+ end
191
+ end
192
+ end
193
+
194
+ # Check if the given MIME is a JSON MIME.
195
+ # JSON MIME examples:
196
+ # application/json
197
+ # application/json; charset=UTF8
198
+ # APPLICATION/JSON
199
+ # */*
200
+ # @param [String] mime MIME
201
+ # @return [Boolean] True if the MIME is application/json
202
+ def json_mime?(mime)
203
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
204
+ end
205
+
206
+ # Deserialize the response to the given return type.
207
+ #
208
+ # @param [Response] response HTTP response
209
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
210
+ def deserialize(response, return_type)
211
+ body = response.body
212
+
213
+ # handle file downloading - return the File instance processed in request callbacks
214
+ # note that response body is empty when the file is written in chunks in request on_body callback
215
+ return @tempfile if return_type == 'File'
216
+
217
+ return nil if body.nil? || body.empty?
218
+
219
+ # return response body directly for String return type
220
+ return body if return_type == 'String'
221
+
222
+ # ensuring a default content type
223
+ content_type = response.headers['Content-Type'] || 'application/json'
224
+
225
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
226
+
227
+ begin
228
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
229
+ rescue JSON::ParserError => e
230
+ if %w(String Date Time).include?(return_type)
231
+ data = body
232
+ else
233
+ raise e
234
+ end
235
+ end
236
+
237
+ convert_to_type data, return_type
238
+ end
239
+
240
+ # Convert data to the given return type.
241
+ # @param [Object] data Data to be converted
242
+ # @param [String] return_type Return type
243
+ # @return [Mixed] Data in a particular type
244
+ def convert_to_type(data, return_type)
245
+ return nil if data.nil?
246
+ case return_type
247
+ when 'String'
248
+ data.to_s
249
+ when 'Integer'
250
+ data.to_i
251
+ when 'Float'
252
+ data.to_f
253
+ when 'Boolean'
254
+ data == true
255
+ when 'Time'
256
+ # parse date time (expecting ISO 8601 format)
257
+ Time.parse data
258
+ when 'Date'
259
+ # parse date time (expecting ISO 8601 format)
260
+ Date.parse data
261
+ when 'Object'
262
+ # generic object (usually a Hash), return directly
263
+ data
264
+ when /\AArray<(.+)>\z/
265
+ # e.g. Array<Pet>
266
+ sub_type = $1
267
+ data.map { |item| convert_to_type(item, sub_type) }
268
+ when /\AHash\<String, (.+)\>\z/
269
+ # e.g. Hash<String, Integer>
270
+ sub_type = $1
271
+ {}.tap do |hash|
272
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
273
+ end
274
+ else
275
+ # models (e.g. Pet) or oneOf
276
+ klass = PokeApiClient.const_get(return_type)
277
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
278
+ end
279
+ end
280
+
281
+ # Sanitize filename by removing path.
282
+ # e.g. ../../sun.gif becomes sun.gif
283
+ #
284
+ # @param [String] filename the filename to be sanitized
285
+ # @return [String] the sanitized filename
286
+ def sanitize_filename(filename)
287
+ filename.gsub(/.*[\/\\]/, '')
288
+ end
289
+
290
+ def build_request_url(path, opts = {})
291
+ # Add leading and trailing slashes to path
292
+ path = "/#{path}".gsub(/\/+/, '/')
293
+ @config.base_url(opts[:operation]) + path
294
+ end
295
+
296
+ # Update header and query params based on authentication settings.
297
+ #
298
+ # @param [Hash] header_params Header parameters
299
+ # @param [Hash] query_params Query parameters
300
+ # @param [String] auth_names Authentication scheme name
301
+ def update_params_for_auth!(header_params, query_params, auth_names)
302
+ Array(auth_names).each do |auth_name|
303
+ auth_setting = @config.auth_settings[auth_name]
304
+ next unless auth_setting
305
+ case auth_setting[:in]
306
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
307
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
308
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
309
+ end
310
+ end
311
+ end
312
+
313
+ # Sets user agent in HTTP header
314
+ #
315
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
316
+ def user_agent=(user_agent)
317
+ @user_agent = user_agent
318
+ @default_headers['User-Agent'] = @user_agent
319
+ end
320
+
321
+ # Return Accept header based on an array of accepts provided.
322
+ # @param [Array] accepts array for Accept
323
+ # @return [String] the Accept header (e.g. application/json)
324
+ def select_header_accept(accepts)
325
+ return nil if accepts.nil? || accepts.empty?
326
+ # use JSON when present, otherwise use all of the provided
327
+ json_accept = accepts.find { |s| json_mime?(s) }
328
+ json_accept || accepts.join(',')
329
+ end
330
+
331
+ # Return Content-Type header based on an array of content types provided.
332
+ # @param [Array] content_types array for Content-Type
333
+ # @return [String] the Content-Type header (e.g. application/json)
334
+ def select_header_content_type(content_types)
335
+ # return nil by default
336
+ return if content_types.nil? || content_types.empty?
337
+ # use JSON when present, otherwise use the first one
338
+ json_content_type = content_types.find { |s| json_mime?(s) }
339
+ json_content_type || content_types.first
340
+ end
341
+
342
+ # Convert object (array, hash, object, etc) to JSON string.
343
+ # @param [Object] model object to be converted into JSON string
344
+ # @return [String] JSON string representation of the object
345
+ def object_to_http_body(model)
346
+ return model if model.nil? || model.is_a?(String)
347
+ local_body = nil
348
+ if model.is_a?(Array)
349
+ local_body = model.map { |m| object_to_hash(m) }
350
+ else
351
+ local_body = object_to_hash(model)
352
+ end
353
+ local_body.to_json
354
+ end
355
+
356
+ # Convert object(non-array) to hash.
357
+ # @param [Object] obj object to be converted into JSON string
358
+ # @return [String] JSON string representation of the object
359
+ def object_to_hash(obj)
360
+ if obj.respond_to?(:to_hash)
361
+ obj.to_hash
362
+ else
363
+ obj
364
+ end
365
+ end
366
+
367
+ # Build parameter value according to the given collection format.
368
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
369
+ def build_collection_param(param, collection_format)
370
+ case collection_format
371
+ when :csv
372
+ param.join(',')
373
+ when :ssv
374
+ param.join(' ')
375
+ when :tsv
376
+ param.join("\t")
377
+ when :pipes
378
+ param.join('|')
379
+ when :multi
380
+ # return the array directly as typhoeus will handle it as expected
381
+ param
382
+ else
383
+ fail "unknown collection format: #{collection_format.inspect}"
384
+ end
385
+ end
386
+ end
387
+ end
@@ -0,0 +1,55 @@
1
+ =begin
2
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
3
+
4
+ The version of the OpenAPI document: 20220523
5
+
6
+ Generated by: https://openapi-generator.tech
7
+ OpenAPI Generator version: 5.4.0
8
+
9
+ =end
10
+
11
+ module PokeApiClient
12
+ class ApiError < StandardError
13
+ attr_reader :code, :response_headers, :response_body
14
+
15
+ # Usage examples:
16
+ # ApiError.new
17
+ # ApiError.new("message")
18
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
19
+ # ApiError.new(:code => 404, :message => "Not Found")
20
+ def initialize(arg = nil)
21
+ if arg.is_a? Hash
22
+ if arg.key?(:message) || arg.key?('message')
23
+ super(arg[:message] || arg['message'])
24
+ else
25
+ super arg
26
+ end
27
+
28
+ arg.each do |k, v|
29
+ instance_variable_set "@#{k}", v
30
+ end
31
+ else
32
+ super arg
33
+ end
34
+ end
35
+
36
+ # Override to_s to display a friendly error message
37
+ def to_s
38
+ message
39
+ end
40
+
41
+ def message
42
+ if @message.nil?
43
+ msg = "Error message: the server returns an error"
44
+ else
45
+ msg = @message
46
+ end
47
+
48
+ msg += "\nHTTP status code: #{code}" if code
49
+ msg += "\nResponse headers: #{response_headers}" if response_headers
50
+ msg += "\nResponse body: #{response_body}" if response_body
51
+
52
+ msg
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,269 @@
1
+ =begin
2
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
3
+
4
+ The version of the OpenAPI document: 20220523
5
+
6
+ Generated by: https://openapi-generator.tech
7
+ OpenAPI Generator version: 5.4.0
8
+
9
+ =end
10
+
11
+ module PokeApiClient
12
+ class Configuration
13
+ # Defines url scheme
14
+ attr_accessor :scheme
15
+
16
+ # Defines url host
17
+ attr_accessor :host
18
+
19
+ # Defines url base path
20
+ attr_accessor :base_path
21
+
22
+ # Define server configuration index
23
+ attr_accessor :server_index
24
+
25
+ # Define server operation configuration index
26
+ attr_accessor :server_operation_index
27
+
28
+ # Default server variables
29
+ attr_accessor :server_variables
30
+
31
+ # Default server operation variables
32
+ attr_accessor :server_operation_variables
33
+
34
+ # Defines API keys used with API Key authentications.
35
+ #
36
+ # @return [Hash] key: parameter name, value: parameter value (API key)
37
+ #
38
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
39
+ # config.api_key['api_key'] = 'xxx'
40
+ attr_accessor :api_key
41
+
42
+ # Defines API key prefixes used with API Key authentications.
43
+ #
44
+ # @return [Hash] key: parameter name, value: API key prefix
45
+ #
46
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
47
+ # config.api_key_prefix['api_key'] = 'Token'
48
+ attr_accessor :api_key_prefix
49
+
50
+ # Defines the username used with HTTP basic authentication.
51
+ #
52
+ # @return [String]
53
+ attr_accessor :username
54
+
55
+ # Defines the password used with HTTP basic authentication.
56
+ #
57
+ # @return [String]
58
+ attr_accessor :password
59
+
60
+ # Defines the access token (Bearer) used with OAuth2.
61
+ attr_accessor :access_token
62
+
63
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
64
+ # details will be logged with `logger.debug` (see the `logger` attribute).
65
+ # Default to false.
66
+ #
67
+ # @return [true, false]
68
+ attr_accessor :debugging
69
+
70
+ # Defines the logger used for debugging.
71
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
72
+ #
73
+ # @return [#debug]
74
+ attr_accessor :logger
75
+
76
+ # Defines the temporary folder to store downloaded files
77
+ # (for API endpoints that have file response).
78
+ # Default to use `Tempfile`.
79
+ #
80
+ # @return [String]
81
+ attr_accessor :temp_folder_path
82
+
83
+ # The time limit for HTTP request in seconds.
84
+ # Default to 0 (never times out).
85
+ attr_accessor :timeout
86
+
87
+ # Set this to false to skip client side validation in the operation.
88
+ # Default to true.
89
+ # @return [true, false]
90
+ attr_accessor :client_side_validation
91
+
92
+ ### TLS/SSL setting
93
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
94
+ # Default to true.
95
+ #
96
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
97
+ #
98
+ # @return [true, false]
99
+ attr_accessor :verify_ssl
100
+
101
+ ### TLS/SSL setting
102
+ # Set this to false to skip verifying SSL host name
103
+ # Default to true.
104
+ #
105
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
106
+ #
107
+ # @return [true, false]
108
+ attr_accessor :verify_ssl_host
109
+
110
+ ### TLS/SSL setting
111
+ # Set this to customize the certificate file to verify the peer.
112
+ #
113
+ # @return [String] the path to the certificate file
114
+ #
115
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
116
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
117
+ attr_accessor :ssl_ca_cert
118
+
119
+ ### TLS/SSL setting
120
+ # Client certificate file (for client certificate)
121
+ attr_accessor :cert_file
122
+
123
+ ### TLS/SSL setting
124
+ # Client private key file (for client certificate)
125
+ attr_accessor :key_file
126
+
127
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
128
+ # Default to nil.
129
+ #
130
+ # @see The params_encoding option of Ethon. Related source code:
131
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
132
+ attr_accessor :params_encoding
133
+
134
+ attr_accessor :inject_format
135
+
136
+ attr_accessor :force_ending_format
137
+
138
+ def initialize
139
+ @scheme = 'https'
140
+ @host = 'pokeapi.co'
141
+ @base_path = ''
142
+ @server_index = 0
143
+ @server_operation_index = {}
144
+ @server_variables = {}
145
+ @server_operation_variables = {}
146
+ @api_key = {}
147
+ @api_key_prefix = {}
148
+ @client_side_validation = true
149
+ @verify_ssl = true
150
+ @verify_ssl_host = true
151
+ @params_encoding = nil
152
+ @cert_file = nil
153
+ @key_file = nil
154
+ @timeout = 0
155
+ @debugging = false
156
+ @inject_format = false
157
+ @force_ending_format = false
158
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
159
+
160
+ yield(self) if block_given?
161
+ end
162
+
163
+ # The default Configuration object.
164
+ def self.default
165
+ @@default ||= Configuration.new
166
+ end
167
+
168
+ def configure
169
+ yield(self) if block_given?
170
+ end
171
+
172
+ def scheme=(scheme)
173
+ # remove :// from scheme
174
+ @scheme = scheme.sub(/:\/\//, '')
175
+ end
176
+
177
+ def host=(host)
178
+ # remove http(s):// and anything after a slash
179
+ @host = host.sub(/https?:\/\//, '').split('/').first
180
+ end
181
+
182
+ def base_path=(base_path)
183
+ # Add leading and trailing slashes to base_path
184
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
185
+ @base_path = '' if @base_path == '/'
186
+ end
187
+
188
+ # Returns base URL for specified operation based on server settings
189
+ def base_url(operation = nil)
190
+ index = server_operation_index.fetch(operation, server_index)
191
+ return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if index == nil
192
+
193
+ server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation])
194
+ end
195
+
196
+ # Gets API key (with prefix if set).
197
+ # @param [String] param_name the parameter name of API key auth
198
+ def api_key_with_prefix(param_name, param_alias = nil)
199
+ key = @api_key[param_name]
200
+ key = @api_key.fetch(param_alias, key) unless param_alias.nil?
201
+ if @api_key_prefix[param_name]
202
+ "#{@api_key_prefix[param_name]} #{key}"
203
+ else
204
+ key
205
+ end
206
+ end
207
+
208
+ # Gets Basic Auth token string
209
+ def basic_auth_token
210
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
211
+ end
212
+
213
+ # Returns Auth Settings hash for api client.
214
+ def auth_settings
215
+ {
216
+ }
217
+ end
218
+
219
+ # Returns an array of Server setting
220
+ def server_settings
221
+ [
222
+ {
223
+ url: "https://pokeapi.co",
224
+ description: "No description provided",
225
+ }
226
+ ]
227
+ end
228
+
229
+ def operation_server_settings
230
+ {
231
+ }
232
+ end
233
+
234
+ # Returns URL based on server settings
235
+ #
236
+ # @param index array index of the server settings
237
+ # @param variables hash of variable and the corresponding value
238
+ def server_url(index, variables = {}, servers = nil)
239
+ servers = server_settings if servers == nil
240
+
241
+ # check array index out of bound
242
+ if (index < 0 || index >= servers.size)
243
+ fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}"
244
+ end
245
+
246
+ server = servers[index]
247
+ url = server[:url]
248
+
249
+ return url unless server.key? :variables
250
+
251
+ # go through variable and assign a value
252
+ server[:variables].each do |name, variable|
253
+ if variables.key?(name)
254
+ if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name]))
255
+ url.gsub! "{" + name.to_s + "}", variables[name]
256
+ else
257
+ fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}."
258
+ end
259
+ else
260
+ # use default value
261
+ url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value]
262
+ end
263
+ end
264
+
265
+ url
266
+ end
267
+
268
+ end
269
+ end