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.
-
.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.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 168 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.
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 92 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.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 246 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
478 479 480 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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 478 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.
312 313 314 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 312 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.
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 203 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
340 341 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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 340 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.
81 82 83 84 85 86 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 81 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
529 530 531 532 533 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 529 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.
63 64 65 66 67 68 69 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 63 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.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 41 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.
30 31 32 33 34 35 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 30 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.
234 235 236 237 238 239 240 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 234 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.
73 74 75 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 73 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.
375 376 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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 375 def self.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED) retval = {} # If this is a structure, resolve it's field names. obj = obj.to_hash if obj.is_a? BaseModel # Create a form encoded hash for this object. if obj.nil? nil 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.
319 320 321 322 323 324 325 326 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 319 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.
449 450 451 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 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 449 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
514 515 516 517 518 519 520 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 514 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 |
.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false) ⇒ Hash, ...
Parses a JSON string.
292 293 294 295 296 297 298 299 300 301 302 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 292 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.
306 307 308 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 306 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
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 425 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.
331 332 333 334 335 336 337 338 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 331 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.
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 562 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.
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 540 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 = JsonPointerHelper.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
523 524 525 526 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 523 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).
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 10 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.
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 130 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.
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
# File 'lib/apimatic-core/utilities/api_helper.rb', line 268 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 |