Class: NContent::SDK::RESTClient

Inherits:
Object
  • Object
show all
Defined in:
lib/ncontent/sdk/rest_client.rb

Constant Summary collapse

CLIENT_TOKEN_CACHE_KEY =
"ncontent/api_client/client_token".freeze

Class Method Summary collapse

Class Method Details

.delete(path = nil, opts = {}, &block) ⇒ Object



73
74
75
# File 'lib/ncontent/sdk/rest_client.rb', line 73

def self.delete(path=nil, opts = {}, &block)
  request(:delete, path, opts, &block)
end

.get(path = nil, opts = {}, &block) ⇒ Object



57
58
59
# File 'lib/ncontent/sdk/rest_client.rb', line 57

def self.get(path=nil, opts = {}, &block)
  request(:get, path, opts, &block)
end

.patch(path = nil, opts = {}, &block) ⇒ Object



69
70
71
# File 'lib/ncontent/sdk/rest_client.rb', line 69

def self.patch(path=nil, opts = {}, &block)
  request(:patch, path, opts, &block)
end

.post(path = nil, opts = {}, &block) ⇒ Object



61
62
63
# File 'lib/ncontent/sdk/rest_client.rb', line 61

def self.post(path=nil, opts = {}, &block)
  request(:post, path, opts, &block)
end

.put(path = nil, opts = {}, &block) ⇒ Object



65
66
67
# File 'lib/ncontent/sdk/rest_client.rb', line 65

def self.put(path=nil, opts = {}, &block)
  request(:put, path, opts, &block)
end

.request(verb, path = nil, opts = {}, &block) ⇒ Object

Make a request to the API:

Parameters:

  • verb (Symbol)

    the HTTP request method

  • path (String) (defaults to: nil)

    the HTTP URL path of the request

  • opts (Hash) (defaults to: {})

    the options to make the request with



21
22
23
24
25
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
# File 'lib/ncontent/sdk/rest_client.rb', line 21

def self.request(verb, path=nil, opts = {}, &block)

  retrying = false

  begin

    # If we beforehand know that the current token expired then the client
    # token should be re-generated.
    reset_oauth_token! if oauth_token.expired?

    oauth_token.request(verb, path, opts) do |req|
      req.options.timeout = config.api_call_timeout
      req.options.open_timeout = config.api_call_open_timeout
      yield req if block_given?
    end

  rescue OAuth2::Error => error
    if error.response.status == 401 && !retrying
      reset_oauth_token!
      retrying = true
      logger.info "Retrying response #{verb.upcase} #{path} with a fresh nContent token."
      retry
    else
      logger.warn "Not retrying response #{verb.upcase} #{path}."

      # Extract from the OAuth::Error the base Faraday response:
      error_response = error.response.response

      # Build the error that will be raised:
      error_to_raise = NaranyaEcm::Rest::RestError.build_from_failed_response(error_response)

      raise error_to_raise
    end
  end
end