Class: Fabricio::Networking::NetworkClient

Inherits:
Object
  • Object
show all
Defined in:
lib/fabricio/networking/network_client.rb

Overview

This class makes network requests based on request models

Instance Method Summary collapse

Constructor Details

#initialize(authorization_client = nil, session_storage = nil) ⇒ Fabricio::Networking::NetworkClient

Initializes a new NetworkClient object

Parameters:



16
17
18
19
20
# File 'lib/fabricio/networking/network_client.rb', line 16

def initialize(authorization_client = nil, session_storage = nil)
  @authorization_client = authorization_client
  @session_storage = session_storage
  @is_refreshing_session = false
end

Instance Method Details

#perform_request(model) ⇒ String

Performs a network request based on a passed request model

Parameters:

Returns:

  • (String)


26
27
28
29
30
31
32
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
# File 'lib/fabricio/networking/network_client.rb', line 26

def perform_request(model)
  session = @session_storage.obtain_session
  model = sign_model(model, session)

  connection = Faraday.new(:url => model.base_url) do |faraday|
    faraday.adapter Faraday.default_adapter
  end

  if model.type == :GET
    result = perform_get_request(connection, model)
  elsif model.type == :POST
    result = perform_post_request(connection, model)
  end

  # If there is an authorization error and we aren't already trying to refresh it, we make a refresh session call and retry the initial network request.
  is_authorization_error = result.success? == false && [401, 402].include?(result.status)
  if is_authorization_error && @is_refreshing_session == false
    refreshed_session = @authorization_client.refresh(session)
    @session_storage.store_session(refreshed_session)

    @is_refreshing_session = true
    return perform_request(model)
  end

  # If authorization returns 401 and refresh session operation failed we throw exception
  if is_authorization_error && @is_refreshing_session == true
    raise StandardError.new('Can`t refresh session. Try once again later or repeat authorization manually')
  end

  if is_authorization_error == false
    @is_refreshing_session = false
  end
  result
end