Module: Invofox

Defined in:
lib/invofox/base.rb,
lib/invofox/version.rb

Defined Under Namespace

Classes: Collection, Company, Configuration, Document, Error, LoadBatch, Resource, Response

Constant Summary collapse

VERSION =
"0.1.6"

Class Method Summary collapse

Class Method Details

.api_call(clazz:, method:, path:, params: {}, &block) ⇒ Object



14
15
16
17
18
19
20
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/invofox/base.rb', line 14

def api_call(clazz:, method:, path:, params: {}, &block)
  # Prepare the URL
  url = 'https://api.invofox.com' + path

  # Prepare headers & params
  request_headers = {
    accept:       'application/json',
    content_type: 'application/json',
    "x-api-key" => Invofox.configuration.api_key
  }

  request_params = {
    headers: request_headers,
    method:  method,
    url:     url,
    timeout: 60 * 5 # a 5m timeout should be enough for anything
  }

  if method == :post || method == :put
    request_params[:payload] = params.to_json
  else
    request_headers[:params] = params
  end

  # Do the request
  response = begin
    RestClient::Request.execute(request_params)
  rescue RestClient::BadRequest, RestClient::ExpectationFailed => bad_request
    bad_request.response
  end

  # Log it
  log_request(
    method: method,
    url:    url,
    params: params
  )

  # Deal with the response
  response_body = JSON.parse(response.body)

  # 1. First, we treat errors if any
  treat_errors_if_any(response_body: response_body)

  # 2. If all went fine, we locate the body result
  result_in_body = block.call(response_body)

  # 3. We build the resource result
  result = if result_in_body.is_a?(Array)
             Collection.new(result_in_body, clazz)
           else
             clazz.new(result_in_body)
           end

  # 4. And return everything together
  Invofox::Response.new(
    result:      result
  )
end

.configurationObject



6
7
8
# File 'lib/invofox/base.rb', line 6

def configuration
  @configuration ||= Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



10
11
12
# File 'lib/invofox/base.rb', line 10

def configure
  yield(configuration)
end

.log_request(method:, url:, params: {}) ⇒ Object



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
# File 'lib/invofox/base.rb', line 74

def log_request(method:, url:, params: {})
  logger = Invofox.configuration.logger
  return if logger.nil?

  now = Time.now

  safe_params = {}
  params.each do |key, value|
    safe_value = value

    if safe_value.is_a?(Symbol)
      safe_value = safe_value.to_s
    end

    safe_params[key] = safe_value
  end

  logger.info(
    message:   'Invofox request',
    method:    method.upcase.to_s,
    url:       url,
    time:      now.to_s,
    timestamp: now.to_i,
    params:    safe_params
  )
end