Class: CoreLibrary::ApiHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/apimatic-core/utilities/api_helper.rb

Overview

API utility class involved in executing an API

Class Method Summary collapse

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.

Parameters:

  • query_builder (String)

    The query string builder to add the query parameters to.

  • parameters (Hash)

    The parameters to append.

  • array_serialization (String) (defaults to: ArraySerializationFormat::INDEXED)

    The serialization format



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
199
# File 'lib/apimatic-core/utilities/api_helper.rb', line 169

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.

Parameters:

  • query_builder (String)

    The query string builder to replace the template

  • parameters (Hash)

    The parameters to replace in the url.



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
125
# File 'lib/apimatic-core/utilities/api_helper.rb', line 93

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.

Parameters:

  • value (String)

    The value to be parsed.

Returns:

  • (Integer, Float, Boolean, String)

    The deserialized value, which can be an Integer, Float, Boolean, or String.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/apimatic-core/utilities/api_helper.rb', line 247

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

.clean_hash(hash) ⇒ Object

Removes elements with empty values from a hash.

Parameters:

  • hash (Hash)

    The hash to clean.



305
306
307
# File 'lib/apimatic-core/utilities/api_helper.rb', line 305

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.

Parameters:

  • url (String)

    The given Url to process.

Returns:

  • (String)

    Pre-processed Url as string.

Raises:

  • (ArgumentError)


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/apimatic-core/utilities/api_helper.rb', line 204

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



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/apimatic-core/utilities/api_helper.rb', line 333

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.

Parameters:

  • response

    The response received.

  • deserialize_into

    The custom model type to deserialize into.

  • is_array

    Is the response provided an array or not



82
83
84
85
86
87
# File 'lib/apimatic-core/utilities/api_helper.rb', line 82

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_typesObject

Array of supported data types



455
456
457
458
459
# File 'lib/apimatic-core/utilities/api_helper.rb', line 455

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.

Parameters:

  • response

    The response received.

  • is_array

    Is the response provided an array or not



64
65
66
67
68
69
70
# File 'lib/apimatic-core/utilities/api_helper.rb', line 64

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.

Parameters:

  • response

    The response received.

  • datetime_format

    Current format of datetime.

  • is_array

    Is the response provided an array or not



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/apimatic-core/utilities/api_helper.rb', line 42

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.

Parameters:

  • response

    The response received.

  • type

    Type to be deserialized.

  • is_array

    Is the response provided an array or not

Raises:

  • (ArgumentError)


31
32
33
34
35
36
# File 'lib/apimatic-core/utilities/api_helper.rb', line 31

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.

Parameters:

  • union_type (UnionType)

    The union type to validate and deserialize the response.

  • response (Object)

    The response object to be deserialized.

  • should_deserialize (Boolean) (defaults to: false)

    Flag indicating whether the response should be deserialized. Default is true.

Returns:

  • (Object)

    The deserialized response based on the union_type.



235
236
237
238
239
240
241
# File 'lib/apimatic-core/utilities/api_helper.rb', line 235

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.

Parameters:

  • response

    The response received.



74
75
76
# File 'lib/apimatic-core/utilities/api_helper.rb', line 74

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.

Parameters:

  • obj (Dynamic)

    An object to form encode.

  • instance_name (String)

    The name of the object.

Returns:

  • (Hash)

    A form encoded representation of the object in the form



368
369
370
371
372
373
374
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
# File 'lib/apimatic-core/utilities/api_helper.rb', line 368

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.

Parameters:

  • form_parameters (Hash)

    The hash of parameters to encode.

Returns:

  • (Hash)

    A hash with the same parameters form encoded.



312
313
314
315
316
317
318
319
# File 'lib/apimatic-core/utilities/api_helper.rb', line 312

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_content_type(value) ⇒ Object

Get content-type depending on the value

Parameters:

  • value (Object)

    The value for which the content-type is resolved.



440
441
442
443
444
445
446
# File 'lib/apimatic-core/utilities/api_helper.rb', line 440

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.

Parameters:

  • json (String)

    A JSON string.

  • should_symbolize (Boolean) (defaults to: false)

    Determines whether the keys should be symbolized. If set to true, the keys will be converted to symbols. Defaults to false.

  • allow_primitive_type_parsing (Boolean) (defaults to: false)

    Determines whether to allow parsing of primitive types. If set to true, the method will attempt to parse primitive types like numbers and booleans. Defaults to false.

Returns:

  • (Hash, Array, nil)

    The parsed JSON object, or nil if the input string is nil.

Raises:

  • (TypeError)

    if the server responds with invalid JSON and primitive type parsing is not allowed.



285
286
287
288
289
290
291
292
293
294
295
# File 'lib/apimatic-core/utilities/api_helper.rb', line 285

def self.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false)
  return if json.nil?

  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.

Parameters:

  • obj (object)

    The object to serialize.



299
300
301
# File 'lib/apimatic-core/utilities/api_helper.rb', line 299

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

Parameters:

  • obj (Hash, Array)

    The hash to extract data from

  • keys (Array<String, Integer>)

    The keys/indexes to use

Returns:

  • (Object)

    The extracted value



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/apimatic-core/utilities/api_helper.rb', line 418

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.

Parameters:

  • query_parameters (Hash)

    The hash of query parameters.

Returns:

  • (Hash)

    array_serialization A hash with the processed query parameters.



324
325
326
327
328
329
330
331
# File 'lib/apimatic-core/utilities/api_helper.rb', line 324

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.

Parameters:

  • placeholders (List)

    The placeholders that need to be searched and replaced in the given template value.

  • values (Hash|String)

    The value which refers to the actual values to replace with.

  • template (String)

    The template string containing placeholders.



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/apimatic-core/utilities/api_helper.rb', line 488

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.

Parameters:

  • placeholders (String)

    The placeholders that need to be searched and replaced in the given template value.

  • value (String)

    The dictionary containing the actual values to replace with.

  • template (String)

    The template string containing placeholders.



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/apimatic-core/utilities/api_helper.rb', line 466

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_typesObject

Array of serializable types



449
450
451
452
# File 'lib/apimatic-core/utilities/api_helper.rb', line 449

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).

Parameters:

  • key (String)

    The name of the parameter.

  • array (Array)

    The value of the parameter.

  • formatting (String) (defaults to: 'indexed')

    The format of the serialization.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/apimatic-core/utilities/api_helper.rb', line 11

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.

Parameters:

  • user_agent (String)

    The user_agent value to be replaced with the given

  • parameters (Hash)

    The parameters to replace in the user_agent.



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
163
# File 'lib/apimatic-core/utilities/api_helper.rb', line 131

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) ⇒ Boolean

Checks if a value or all values in a nested structure satisfy a given type condition.

Parameters:

  • value (Object)

    The value or nested structure to be checked.

  • type_callable (Proc)

    A callable object that defines the type condition.

Returns:

  • (Boolean)

    Returns true if the value or all values in the structure satisfy the type condition, false otherwise.



267
268
269
270
271
272
273
274
275
# File 'lib/apimatic-core/utilities/api_helper.rb', line 267

def self.valid_type?(value, type_callable)
  if value.is_a?(Array)
    value.all? { |item| valid_type?(item, type_callable) }
  elsif value.is_a?(Hash)
    value.values.all? { |item| valid_type?(item, type_callable) }
  else
    !value.nil? && type_callable.call(value)
  end
end