Class: CoreLibrary::ApiHelper
- Inherits:
-
Object
- Object
- CoreLibrary::ApiHelper
- Defined in:
- lib/apimatic-core/utilities/api_helper.rb
Overview
API utility class involved in executing an API
Class Method Summary collapse
-
.append_url_with_query_parameters(query_builder, parameters, array_serialization = ArraySerializationFormat::INDEXED) ⇒ Object
Appends the given set of parameters to the given query string.
-
.append_url_with_template_parameters(query_builder, parameters) ⇒ Object
Replaces template parameters in the given url.
-
.apply_primitive_type_parser(value) ⇒ Integer, ...
Applies a primitive type parser to deserialize a value.
- .apply_unboxing_function(obj, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Object
-
.clean_hash(hash) ⇒ Object
Removes elements with empty values from a hash.
-
.clean_url(url) ⇒ String
Validates and processes the given Url.
- .custom_merge(a, b) ⇒ Object
-
.custom_type_deserializer(response, deserialize_into, is_array, should_symbolize) ⇒ Object
Deserializes response to a known custom model type.
-
.data_types ⇒ Object
Array of supported data types.
-
.date_deserializer(response, is_array, should_symbolize) ⇒ Object
Deserializes date.
-
.deserialize_datetime(response, datetime_format, is_array, should_symbolize) ⇒ Object
Deserializes datetime.
-
.deserialize_primitive_types(response, type, is_array, should_symbolize) ⇒ Object
Deserializes primitive types like Boolean, String etc.
-
.deserialize_union_type(union_type, response, should_symbolize = false, should_deserialize = false) ⇒ Object
Deserialize the response based on the provided union_type.
-
.dynamic_deserializer(response, should_symbolize) ⇒ Object
Deserializer to use when the type of response is not known beforehand.
-
.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED) ⇒ Hash
Form encodes an object.
-
.form_encode_parameters(form_parameters, array_serialization) ⇒ Hash
Form encodes a hash of parameters.
-
.get_additional_properties(hash, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Hash
Apply unboxing_function to additional properties from hash.
-
.get_content_type(value) ⇒ Object
Get content-type depending on the value.
-
.get_query_parameters(url) ⇒ Object
Parses query parameters from a given URL.
-
.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false) ⇒ Hash, ...
Parses a JSON string.
-
.json_serialize(obj) ⇒ Object
Parses JSON string.
-
.map_response(obj, keys) ⇒ Object
Retrieves a field from a Hash/Array based on an Array of keys/indexes.
-
.process_complex_types_parameters(query_parameters, array_serialization) ⇒ Hash
Process complex types in query_params.
-
.resolve_template_placeholders(placeholders, values, template) ⇒ Object
Updates all placeholders in the given message template with provided value.
-
.resolve_template_placeholders_using_json_pointer(placeholders, value, template) ⇒ Object
Updates all placeholders in the given message template with provided value.
-
.serializable_types ⇒ Object
Array of serializable types.
-
.serialize_array(key, array, formatting: 'indexed') ⇒ Object
Serializes an array parameter (creates key value pairs).
-
.update_user_agent_value_with_parameters(user_agent, parameters) ⇒ Object
Replaces the template parameters in the given user-agent string.
-
.valid_type?(value, type_callable, is_model_hash: false, is_inner_model_hash: false) ⇒ Boolean
Checks if a value or all values in a nested structure satisfy a given type condition.
Class Method Details
.append_url_with_query_parameters(query_builder, parameters, array_serialization = ArraySerializationFormat::INDEXED) ⇒ Object
Appends the given set of parameters to the given query string.
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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 170 def self.append_url_with_query_parameters(query_builder, parameters, array_serialization = ArraySerializationFormat::INDEXED) # Perform parameter validation. unless query_builder.instance_of? String raise ArgumentError, 'Given value for parameter \"query_builder\" is invalid.' end # Return if there are no parameters to replace. return query_builder if parameters.nil? parameters = process_complex_types_parameters(parameters, array_serialization) parameters.each do |key, value| seperator = query_builder.include?('?') ? '&' : '?' unless value.nil? if value.instance_of? Array value.compact! serialize_array( key, value, formatting: array_serialization ).each do |element| seperator = query_builder.include?('?') ? '&' : '?' query_builder += "#{seperator}#{element[0]}=#{element[1]}" end else query_builder += "#{seperator}#{key}=#{CGI.escape(value.to_s)}" end end end query_builder end |
.append_url_with_template_parameters(query_builder, parameters) ⇒ Object
Replaces template parameters in the given url. parameters.
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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 94 def self.append_url_with_template_parameters(query_builder, parameters) # perform parameter validation unless query_builder.instance_of? String raise ArgumentError, 'Given value for parameter \"query_builder\" is invalid.' end # Return if there are no parameters to replace. return query_builder if parameters.nil? parameters.each do |key, val| if val.nil? replace_value = '' elsif val['value'].instance_of? Array if val['encode'] == true val['value'].map! { |element| CGI.escape(element.to_s) } else val['value'].map!(&:to_s) end replace_value = val['value'].join('/') else replace_value = if val['encode'] == true CGI.escape(val['value'].to_s) else val['value'].to_s end end # Find the template parameter and replace it with its value. query_builder = query_builder.gsub("{#{key}}", replace_value) end query_builder end |
.apply_primitive_type_parser(value) ⇒ Integer, ...
Applies a primitive type parser to deserialize a value.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 248 def self.apply_primitive_type_parser(value) # Attempt to deserialize as Integer return value.to_i if value.match?(/^\d+$/) # Attempt to deserialize as Float return value.to_f if value.match?(/^\d+(\.\d+)?$/) # Attempt to deserialize as Boolean return true if value.downcase == 'true' return false if value.downcase == 'false' # Default: return the original string value end |
.apply_unboxing_function(obj, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Object
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 481 def self.apply_unboxing_function(obj, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) if is_dict if is_map_of_array # Handle case where the object is a map of arrays (Hash with array values) obj.transform_values do |v| apply_unboxing_function(v, unboxing_function, is_array: true, dimension_count: dimension_count) end else # Handle regular Hash (map) case obj.transform_values { |v| unboxing_function.call(v) } end elsif is_array if is_array_of_map # Handle case where the object is an array of maps (Array of Hashes) obj.map do |element| apply_unboxing_function(element, unboxing_function, is_dict: true, dimension_count: dimension_count) end elsif dimension_count > 1 # Handle multi-dimensional array obj.map do |element| apply_unboxing_function(element, unboxing_function, is_array: true, dimension_count: dimension_count - 1) end else # Handle regular Array case obj.map { |element| unboxing_function.call(element) } end else # Handle base case where the object is neither Array nor Hash unboxing_function.call(obj) end end |
.clean_hash(hash) ⇒ Object
Removes elements with empty values from a hash.
314 315 316 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 314 def self.clean_hash(hash) hash.delete_if { |_key, value| value.to_s.strip.empty? } end |
.clean_url(url) ⇒ String
Validates and processes the given Url.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 205 def self.clean_url(url) # Perform parameter validation. raise ArgumentError, 'Invalid Url.' unless url.instance_of? String # Ensure that the urls are absolute. matches = url.match(%r{^(https?://[^/]+)}) raise ArgumentError, 'Invalid Url format.' if matches.nil? # Get the http protocol match. protocol = matches[1] # Check if parameters exist. index = url.index('?') # Remove redundant forward slashes. query = url[protocol.length...(!index.nil? ? index : url.length)] query.gsub!(%r{//+}, '/') # Get the parameters. parameters = !index.nil? ? url[url.index('?')...url.length] : '' # Return processed url. protocol + query + parameters end |
.custom_merge(a, b) ⇒ Object
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 342 def self.custom_merge(a, b) x = {} a.each do |key, value_a| b.each do |k, value_b| next unless key == k x[k] = [] if value_a.instance_of? Array value_a.each do |v| x[k].push(v) end else x[k].push(value_a) end if value_b.instance_of? Array value_b.each do |v| x[k].push(v) end else x[k].push(value_b) end a.delete(k) b.delete(k) end end x.merge!(a) x.merge!(b) x end |
.custom_type_deserializer(response, deserialize_into, is_array, should_symbolize) ⇒ Object
Deserializes response to a known custom model type.
83 84 85 86 87 88 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 83 def self.custom_type_deserializer(response, deserialize_into, is_array, should_symbolize) decoded = json_deserialize(response, should_symbolize) return deserialize_into.call(decoded) unless is_array decoded.map { |element| deserialize_into.call(element) } end |
.data_types ⇒ Object
Array of supported data types
532 533 534 535 536 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 532 def self.data_types [String, Float, Integer, TrueClass, FalseClass, Date, DateTime, Array, Hash, Object] end |
.date_deserializer(response, is_array, should_symbolize) ⇒ Object
Deserializes date.
65 66 67 68 69 70 71 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 65 def self.date_deserializer(response, is_array, should_symbolize) if is_array decoded = json_deserialize(response, should_symbolize) return decoded.map { |element| Date.iso8601(element) } end Date.iso8601(response) end |
.deserialize_datetime(response, datetime_format, is_array, should_symbolize) ⇒ Object
Deserializes datetime.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 43 def self.deserialize_datetime(response, datetime_format, is_array, should_symbolize) decoded = json_deserialize(response, should_symbolize) if is_array case datetime_format when DateTimeFormat::HTTP_DATE_TIME return DateTimeHelper.from_rfc1123(response) unless is_array decoded.map { |element| DateTimeHelper.from_rfc1123(element) } when DateTimeFormat::RFC3339_DATE_TIME return DateTimeHelper.from_rfc3339(response) unless is_array decoded.map { |element| DateTimeHelper.from_rfc3339(element) } when DateTimeFormat::UNIX_DATE_TIME return DateTimeHelper.from_unix(response) unless is_array decoded.map { |element| DateTimeHelper.from_unix(element) } end end |
.deserialize_primitive_types(response, type, is_array, should_symbolize) ⇒ Object
Deserializes primitive types like Boolean, String etc.
32 33 34 35 36 37 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 32 def self.deserialize_primitive_types(response, type, is_array, should_symbolize) return json_deserialize(response, should_symbolize) if is_array raise ArgumentError, 'callable has not been not provided for deserializer.' if type.nil? type.call(response) end |
.deserialize_union_type(union_type, response, should_symbolize = false, should_deserialize = false) ⇒ Object
Deserialize the response based on the provided union_type.
236 237 238 239 240 241 242 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 236 def self.deserialize_union_type(union_type, response, should_symbolize = false, should_deserialize = false) response = ApiHelper.json_deserialize(response, false, true) if should_deserialize union_type_result = union_type.validate(response) union_type_result.deserialize(response, should_symbolize: should_symbolize) end |
.dynamic_deserializer(response, should_symbolize) ⇒ Object
Deserializer to use when the type of response is not known beforehand.
75 76 77 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 75 def self.dynamic_deserializer(response, should_symbolize) json_deserialize(response, should_symbolize) unless response.nil? || response.to_s.strip.empty? end |
.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED) ⇒ Hash
Form encodes an object. of a hash.
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 377 def self.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED) retval = {} # If this is a structure, resolve its field names. obj = obj.to_hash if obj.is_a? BaseModel # Create a form encoded hash for this object. if obj.nil? return retval elsif obj.instance_of? Array if formatting == ArraySerializationFormat::INDEXED obj.each_with_index do |value, index| retval.merge!(form_encode(value, "#{instance_name}[#{index}]")) end elsif serializable_types.map { |x| obj[0].is_a? x }.any? obj.each do |value| abc = if formatting == ArraySerializationFormat::UN_INDEXED form_encode(value, "#{instance_name}[]", formatting: formatting) else form_encode(value, instance_name, formatting: formatting) end retval = custom_merge(retval, abc) end else obj.each_with_index do |value, index| retval.merge!(form_encode(value, "#{instance_name}[#{index}]", formatting: formatting)) end end elsif obj.instance_of? Hash obj.each do |key, value| retval.merge!(form_encode(value, "#{instance_name}[#{key}]", formatting: formatting)) end elsif obj.instance_of? File retval[instance_name] = UploadIO.new( obj, 'application/octet-stream', File.basename(obj.path) ) else retval[instance_name] = obj end retval end |
.form_encode_parameters(form_parameters, array_serialization) ⇒ Hash
Form encodes a hash of parameters.
321 322 323 324 325 326 327 328 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 321 def self.form_encode_parameters(form_parameters, array_serialization) encoded = {} form_parameters.each do |key, value| encoded.merge!(form_encode(value, key, formatting: array_serialization)) end encoded end |
.get_additional_properties(hash, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Hash
Apply unboxing_function to additional properties from hash.
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 452 def self.get_additional_properties(hash, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) additional_properties = {} # Iterate over each key-value pair in the input hash hash.each do |key, value| # Prepare arguments for apply_unboxing_function args = { is_array: is_array, is_dict: is_dict, is_array_of_map: is_array_of_map, is_map_of_array: is_map_of_array, dimension_count: dimension_count } # If the value is a complex structure (Hash or Array), apply apply_unboxing_function additional_properties[key] = if is_array || is_dict apply_unboxing_function(value, unboxing_function, **args) else # Apply the unboxing function directly for simple values unboxing_function.call(value) end rescue StandardError # Ignore the exception and continue processing end additional_properties end |
.get_content_type(value) ⇒ Object
Get content-type depending on the value
517 518 519 520 521 522 523 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 517 def self.get_content_type(value) if serializable_types.map { |x| value.is_a? x }.any? 'text/plain; charset=utf-8' else 'application/json; charset=utf-8' end end |
.get_query_parameters(url) ⇒ Object
Parses query parameters from a given URL. Returns a Hash with decoded keys and values. If a key has multiple values, they are returned as an array.
Example:
ApiHelper.get_query_parameters("https://example.com?a=1&b=2&b=3")
=> {"a"=>"1", "b"=>["2", "3"]}
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 594 def self.get_query_parameters(url) return {} if url.nil? || url.strip.empty? begin uri = URI.parse(url) query = uri.query return {} if query.nil? || query.strip.empty? parsed = CGI.parse(query) # Convert arrays to string or handle empty ones as "" parsed.transform_values! do |v| if v.empty? '' elsif v.size == 1 v.first else v end end rescue URI::InvalidURIError => e warn "Invalid URL provided: #{e.message}" {} rescue StandardError => e warn "Unexpected error while parsing URL: #{e.message}" {} end end |
.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false) ⇒ Hash, ...
Parses a JSON string.
294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 294 def self.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false) return if json.nil? || json.to_s.strip.empty? begin JSON.parse(json, symbolize_names: should_symbolize) rescue StandardError raise TypeError, 'Server responded with invalid JSON.' unless allow_primitive_type_parsing ApiHelper.apply_primitive_type_parser(json) end end |
.json_serialize(obj) ⇒ Object
Parses JSON string.
308 309 310 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 308 def self.json_serialize(obj) serializable_types.map { |x| obj.is_a? x }.any? ? obj.to_s : obj.to_json end |
.map_response(obj, keys) ⇒ Object
Retrieves a field from a Hash/Array based on an Array of keys/indexes
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 428 def self.map_response(obj, keys) val = obj begin keys.each do |key| val = if val.is_a? Array if key.to_i.to_s == key val[key.to_i] else val = nil end else val.fetch(key.to_sym) end end rescue NoMethodError, TypeError, IndexError val = nil end val end |
.process_complex_types_parameters(query_parameters, array_serialization) ⇒ Hash
Process complex types in query_params.
333 334 335 336 337 338 339 340 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 333 def self.process_complex_types_parameters(query_parameters, array_serialization) processed_params = {} query_parameters.each do |key, value| processed_params.merge!(ApiHelper.form_encode(value, key, formatting: array_serialization)) end processed_params end |
.resolve_template_placeholders(placeholders, values, template) ⇒ Object
Updates all placeholders in the given message template with provided value. @@return [String] The resolved template value.
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 565 def self.resolve_template_placeholders(placeholders, values, template) values = values.map { |key, value| [key.to_s, value.to_s] }.to_h if values.is_a? Hash placeholders.each do |placeholder| extracted_value = '' if values.is_a? Hash # pick the last chunk then strip the last character (i.e. `}`) of the string value key = if placeholder.include? '.' placeholder.split('.')[-1].delete_suffix('}') else placeholder.delete_prefix('{').delete_suffix('}') end extracted_value = values[key] unless values[key].nil? else extracted_value = values unless values.nil? end template.gsub!(placeholder, extracted_value.to_s) end template end |
.resolve_template_placeholders_using_json_pointer(placeholders, value, template) ⇒ Object
Updates all placeholders in the given message template with provided value. @@return [String] The resolved template value.
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 543 def self.resolve_template_placeholders_using_json_pointer(placeholders, value, template) placeholders.each do |placeholder| extracted_value = '' if placeholder.include? '#' # pick the 2nd chunk then remove the last character (i.e. `}`) of the string value node_pointer = placeholder.split('#')[1].delete_suffix('}') value_pointer = JsonPointer.new(value, node_pointer, symbolize_keys: true) extracted_value = json_serialize(value_pointer.value) if value_pointer.exists? elsif !value.nil? extracted_value = json_serialize(value) end template.gsub!(placeholder, extracted_value) end template end |
.serializable_types ⇒ Object
Array of serializable types
526 527 528 529 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 526 def self.serializable_types [String, Numeric, TrueClass, FalseClass, Date, DateTime] end |
.serialize_array(key, array, formatting: 'indexed') ⇒ Object
Serializes an array parameter (creates key value pairs).
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 12 def self.serialize_array(key, array, formatting: 'indexed') tuples = [] tuples += case formatting when 'csv' [[key, array.map { |element| CGI.escape(element.to_s) }.join(',')]] when 'psv' [[key, array.map { |element| CGI.escape(element.to_s) }.join('|')]] when 'tsv' [[key, array.map { |element| CGI.escape(element.to_s) }.join("\t")]] else array.map { |element| [key, element] } end tuples end |
.update_user_agent_value_with_parameters(user_agent, parameters) ⇒ Object
Replaces the template parameters in the given user-agent string. parameters.
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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 132 def self.update_user_agent_value_with_parameters(user_agent, parameters) # perform parameter validation unless user_agent.instance_of? String raise ArgumentError, 'Given value for \"user_agent\" is invalid.' end # Return if there are no parameters to replace. return user_agent if parameters.nil? parameters.each do |key, val| if val.nil? replace_value = '' elsif val['value'].instance_of? Array if val['encode'] == true val['value'].map! { |element| ERB::Util.url_encode(element.to_s) } else val['value'].map!(&:to_s) end replace_value = val['value'].join('/') else replace_value = if val['encode'] == true ERB::Util.url_encode(val['value'].to_s) else val['value'].to_s end end # Find the template parameter and replace it with its value. user_agent = user_agent.gsub(key.to_s, replace_value) end user_agent end |
.valid_type?(value, type_callable, is_model_hash: false, is_inner_model_hash: false) ⇒ Boolean
Checks if a value or all values in a nested structure satisfy a given type condition.
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 270 def self.valid_type?(value, type_callable, is_model_hash: false, is_inner_model_hash: false) if value.is_a?(Array) value.all? do |item| valid_type?(item, type_callable, is_model_hash: is_model_hash, is_inner_model_hash: is_inner_model_hash) end elsif value.is_a?(Hash) && (!is_model_hash || is_inner_model_hash) value.values.all? do |item| valid_type?(item, type_callable, is_model_hash: is_model_hash) end else !value.nil? && type_callable.call(value) end end |