Class: ApimaticCalculator::APIHelper
- Inherits:
-
Object
- Object
- ApimaticCalculator::APIHelper
- Defined in:
- lib/apimatic_calculator/api_helper.rb
Overview
API utility class
Class Method Summary collapse
-
.append_url_with_query_parameters(query_builder, parameters) ⇒ 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.
-
.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
-
.data_types ⇒ Object
Array of supported data types.
-
.deserialize(template, value) ⇒ Object
Deserialize the value against the template (group of types).
-
.form_encode(obj, instance_name, formatting: 'indexed') ⇒ Hash
Form encodes an object.
-
.form_encode_parameters(form_parameters) ⇒ Hash
Form encodes a hash of parameters.
-
.get_content_type(value) ⇒ Object
Get content-type depending on the value.
-
.json_deserialize(json) ⇒ Object
Parses JSON string.
-
.json_serialize(obj) ⇒ Object
Parses JSON string.
-
.map_array_type(value, type, group_name, matches) ⇒ Object
Validates and processes the value against the [Array] type.
-
.map_complex_type(value, type, matches) ⇒ Object
Validates and processes the value against the complex types.
-
.map_data_type(value, element, matches) ⇒ Object
Validates and processes the value against the data types.
-
.map_hash_type(value, type, group_name, matches) ⇒ Object
Validates and processes the value against the [Hash] type.
-
.map_response(obj, keys) ⇒ Object
Retrieves a field from a Hash/Array based on an Array of keys/indexes.
-
.map_type(value, type, _group_name, matches) ⇒ Object
Validates and processes the value against the type.
-
.map_types(value, template, group_name: nil) ⇒ Object
Validates and processes the value against the template(group of types).
-
.process_complex_types_parameters(query_parameters, array_serialization) ⇒ Hash
Process complex types in query_params.
-
.serializable_types ⇒ Object
Array of serializable types.
-
.serialize_array(key, array, formatting: 'indexed') ⇒ Object
Serializes an array parameter (creates key value pairs).
-
.validate_types(value, template) ⇒ Object
Validates the value against the template(group of types).
Class Method Details
.append_url_with_query_parameters(query_builder, parameters) ⇒ Object
Appends the given set of parameters to the given query string.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/apimatic_calculator/api_helper.rb', line 70 def self.append_url_with_query_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? array_serialization = 'indexed' 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! APIHelper.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.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/apimatic_calculator/api_helper.rb', line 33 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 |
.clean_hash(hash) ⇒ Object
Removes elements with empty values from a hash.
146 147 148 |
# File 'lib/apimatic_calculator/api_helper.rb', line 146 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.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/apimatic_calculator/api_helper.rb', line 105 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
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 201 202 203 |
# File 'lib/apimatic_calculator/api_helper.rb', line 175 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 |
.data_types ⇒ Object
Array of supported data types
443 444 445 446 447 |
# File 'lib/apimatic_calculator/api_helper.rb', line 443 def self.data_types [String, Float, Integer, TrueClass, FalseClass, Date, DateTime, Array, Hash, Object] end |
.deserialize(template, value) ⇒ Object
Deserialize the value against the template (group of types). against which the value will be mapped (oneOf(Integer, String)).
284 285 286 287 |
# File 'lib/apimatic_calculator/api_helper.rb', line 284 def self.deserialize(template, value) decoded = APIHelper.json_deserialize(value) map_types(decoded, template) end |
.form_encode(obj, instance_name, formatting: 'indexed') ⇒ Hash
Form encodes an object. of a hash.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/apimatic_calculator/api_helper.rb', line 210 def self.form_encode(obj, instance_name, formatting: '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 == 'indexed' obj.each_with_index do |value, index| retval.merge!(APIHelper.form_encode(value, "#{instance_name}[#{index}]")) end elsif APIHelper.serializable_types.map { |x| obj[0].is_a? x }.any? obj.each do |value| abc = if formatting == 'unindexed' APIHelper.form_encode(value, "#{instance_name}[]", formatting: formatting) else APIHelper.form_encode(value, instance_name, formatting: formatting) end retval = APIHelper.custom_merge(retval, abc) end else obj.each_with_index do |value, index| retval.merge!(APIHelper.form_encode(value, "#{instance_name}[#{index}]", formatting: formatting)) end end elsif obj.instance_of? Hash obj.each do |key, value| retval.merge!(APIHelper.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) ⇒ Hash
Form encodes a hash of parameters.
153 154 155 156 157 158 159 160 161 |
# File 'lib/apimatic_calculator/api_helper.rb', line 153 def self.form_encode_parameters(form_parameters) array_serialization = 'indexed' encoded = {} form_parameters.each do |key, value| encoded.merge!(APIHelper.form_encode(value, key, formatting: array_serialization)) end encoded end |
.get_content_type(value) ⇒ Object
Get content-type depending on the value
428 429 430 431 432 433 434 |
# File 'lib/apimatic_calculator/api_helper.rb', line 428 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) ⇒ Object
Parses JSON string.
132 133 134 135 136 |
# File 'lib/apimatic_calculator/api_helper.rb', line 132 def self.json_deserialize(json) JSON.parse(json) rescue StandardError raise TypeError, 'Server responded with invalid JSON.' end |
.json_serialize(obj) ⇒ Object
Parses JSON string.
140 141 142 |
# File 'lib/apimatic_calculator/api_helper.rb', line 140 def self.json_serialize(obj) serializable_types.map { |x| obj.is_a? x }.any? ? obj.to_s : obj.to_json end |
.map_array_type(value, type, group_name, matches) ⇒ Object
Validates and processes the value against the [Array] type.
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'lib/apimatic_calculator/api_helper.rb', line 362 def self.map_array_type(value, type, group_name, matches) if value.instance_of? Array decoded = [] value.each do |val| type = type.chomp('[]').to_s val = map_types(val, type, group_name: group_name) decoded.append(val) unless type.empty? rescue ValidationException next end matches += 1 if decoded.length == value.length value = decoded unless decoded.empty? end [value, matches] end |
.map_complex_type(value, type, matches) ⇒ Object
Validates and processes the value against the complex types.
398 399 400 401 402 403 404 405 406 407 |
# File 'lib/apimatic_calculator/api_helper.rb', line 398 def self.map_complex_type(value, type, matches) obj = ApimaticCalculator.const_get(type) value = if obj.respond_to? 'from_hash' obj.send('from_hash', value) else obj.constants.find { |k| obj.const_get(k) == value } end matches += 1 unless value.nil? [value, matches] end |
.map_data_type(value, element, matches) ⇒ Object
Validates and processes the value against the data types.
413 414 415 416 417 418 |
# File 'lib/apimatic_calculator/api_helper.rb', line 413 def self.map_data_type(value, element, matches) element = element.split('|').map { |x| Object.const_get x } matches += 1 if element.all? { |x| APIHelper.data_types.include?(x) } && element.any? { |x| (value.instance_of? x) || (value.class.ancestors.include? x) } [value, matches] end |
.map_hash_type(value, type, group_name, matches) ⇒ Object
Validates and processes the value against the [Hash] type.
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
# File 'lib/apimatic_calculator/api_helper.rb', line 341 def self.map_hash_type(value, type, group_name, matches) if value.instance_of? Hash decoded = {} value.each do |key, val| type = type.chomp('{}').to_s val = map_types(val, type, group_name: group_name) decoded[key] = val unless type.empty? rescue ValidationException next end matches += 1 if decoded.length == value.length value = decoded unless decoded.empty? end [value, matches] end |
.map_response(obj, keys) ⇒ Object
Retrieves a field from a Hash/Array based on an Array of keys/indexes
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'lib/apimatic_calculator/api_helper.rb', line 260 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 |
.map_type(value, type, _group_name, matches) ⇒ Object
Validates and processes the value against the type.
383 384 385 386 387 388 389 390 391 392 |
# File 'lib/apimatic_calculator/api_helper.rb', line 383 def self.map_type(value, type, _group_name, matches) if ApimaticCalculator.constants.select do |c| ApimaticCalculator.const_get(c).to_s == "ApimaticCalculator::#{type}" end.empty? value, matches = map_data_type(value, type, matches) else value, matches = map_complex_type(value, type, matches) end [value, matches] end |
.map_types(value, template, group_name: nil) ⇒ Object
Validates and processes the value against the template(group of types).
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/apimatic_calculator/api_helper.rb', line 293 def self.map_types(value, template, group_name: nil) result_value = nil matches = 0 types = [] group_name = template.partition('(').first if group_name.nil? && template.match?(/anyOf|oneOf/) return if value.nil? if template.end_with?('{}') || template.end_with?('[]') types = template.split(group_name, 2).last.gsub(/\s+/, '').split else template = template.split(group_name, 2).last.delete_prefix('(').delete_suffix(')') types = template.scan(/(anyOf|oneOf)[(]([^[)]]*)[)]/).flatten.combination(2).map { |a, b| "#{a}(#{b})" } types.each { |t| template = template.gsub(", #{t}", '') } types = template.gsub(/\s+/, '').split(',').push(*types) end types.each do |element| if element.match?(/^(oneOf|anyOf)[(].*$/) begin result_value = map_types(value, element, matches) matches += 1 rescue ValidationException next end elsif element.end_with?('{}') result_value, matches = map_hash_type(value, element, group_name, matches) elsif element.end_with?('[]') result_value, matches = map_array_type(value, element, group_name, matches) else begin result_value, matches = map_type(value, element, group_name, matches) rescue StandardError next end end break if group_name == 'anyOf' && matches == 1 end raise ValidationException.new(value, template) unless matches == 1 value = result_value unless result_value.nil? value end |
.process_complex_types_parameters(query_parameters, array_serialization) ⇒ Hash
Process complex types in query_params.
166 167 168 169 170 171 172 173 |
# File 'lib/apimatic_calculator/api_helper.rb', line 166 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 |
.serializable_types ⇒ Object
Array of serializable types
437 438 439 440 |
# File 'lib/apimatic_calculator/api_helper.rb', line 437 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).
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/apimatic_calculator/api_helper.rb', line 13 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 |
.validate_types(value, template) ⇒ Object
Validates the value against the template(group of types).
423 424 425 |
# File 'lib/apimatic_calculator/api_helper.rb', line 423 def self.validate_types(value, template) map_types(APIHelper.json_deserialize(value.to_json), template) end |