Module: BeyondApi::Utils

Instance Method Summary collapse

Instance Method Details

#file_content_type(file_path) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/beyond_api/utils.rb', line 9

def file_content_type(file_path)
  case File.extname(file_path)
  when ".png"
    "image/png"
  when ".jpg", ".jpeg"
    "image/jpeg"
  when ".gif"
    "image/gif"
  end
end

#handle_all_request(url, resource, params = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/beyond_api/utils.rb', line 20

def handle_all_request(url, resource, params = {})
  paginated_size = BeyondApi.configuration.all_pagination_size

  if params[:paginated] == false
    result = all_paginated(url, params.merge(page: 0, size: paginated_size))

    (1..result[:page][:total_pages] - 1).each do |page|
      result[:embedded][resource].concat(
        all_paginated(url,
                      params.merge(page: page,
                                   size: paginated_size))[:embedded][resource]
      )
    end

    result[:page][:size] = result[:page][:total_elements]
    result[:page][:total_pages] = 1
    result[:page][:number] = 0

    result
  else
    all_paginated(url, params)
  end
end

#handle_error(response, status) ⇒ Object



44
45
46
47
48
# File 'lib/beyond_api/utils.rb', line 44

def handle_error(response, status)
  BeyondApi.logger.error "[Beyond API] #{status}: #{response}"
  error = BeyondApi::Error.new(response, status)
  BeyondApi.configuration.raise_error_requests ? raise(error) : error
end

#handle_response(response, status, respond_with_true: false) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/beyond_api/utils.rb', line 50

def handle_response(response, status, respond_with_true: false)
  if status.between?(200, 299)
    return true if respond_with_true

    response = sanitize_response(response)
    BeyondApi.configuration.object_struct_responses ? to_object_struct(response) : response
  else
    handle_error(response, status)
  end
end

#sanitize_key(key) ⇒ Object



61
62
63
# File 'lib/beyond_api/utils.rb', line 61

def sanitize_key(key)
  key.chars.first == "_" ? key[1..-1] : key
end

#sanitize_response(hash) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/beyond_api/utils.rb', line 65

def sanitize_response(hash)
  {}.tap do |h|
    hash.each do |key, value|
      next if key == "_links" && BeyondApi.configuration.remove_response_links

      key = sanitize_key(key) if BeyondApi.configuration.remove_response_key_underscores
      h[key.underscore.to_sym] = transform(value)
    end
  end
end

#to_object_struct(data) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/beyond_api/utils.rb', line 76

def to_object_struct(data)
  if data.is_a? Hash
    OpenStruct.new(data.map { |key, val| [key, to_object_struct(val)] }.to_h)
  elsif data.is_a? Array
    data.map { |o| to_object_struct(o) }
  else
    data
  end
end