Class: BrightpearlApi::Client

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/brightpearl_api/client.rb

Constant Summary collapse

@@token =
false

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.instanceObject



11
12
13
# File 'lib/brightpearl_api/client.rb', line 11

def self.instance
  @@instance ||= new
end

Instance Method Details

#api_call(type, path, data = {}) ⇒ Object



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
# File 'lib/brightpearl_api/client.rb', line 29

def api_call(type, path, data = {})
  token = authenticate

  uri = configuration.uri(path)
  options = {
    :headers => {
      'Content-Type' => 'application/json',
      'Accept' => 'json',
      'brightpearl-auth' => token
    },
    :body => data.to_json
  }
  if type == :get
    response = HTTParty.get(uri, options)
  elsif type == :post
    response = HTTParty.post(uri, options)
  elsif type == :put
    response = HTTParty.put(uri, options)
  elsif type == :options
    http = Curl.options(uri) do|http|
      http.headers = options[:headers]
    end
    response = JSON.parse(http.body_str)
  elsif type == :delete
    response = HTTParty.delete(uri, options)
  end
  check_response(response)
  return response["response"]
end

#authenticateObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/brightpearl_api/client.rb', line 59

def authenticate
  return @@token unless @@token.blank?
  options = {
    :headers => {
      'Content-Type' => 'application/json',
      'Accept' => 'json'
    },
    :body => {
      :apiAccountCredentials => {
        :emailAddress => configuration.email,
        :password => configuration.password
      }
    }.to_json
  }
  response = HTTParty.post(configuration.auth_uri, options)
  check_response(response)
  @@token = response["response"]
end

#call(type, path, data = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/brightpearl_api/client.rb', line 15

def call(type, path, data = {})
  api_call(type, path, data)
rescue AuthException => e
  reset_token
  api_call(type, path, data)
rescue ThrottleException => e
  sleep(60.seconds)
  reset_token
  api_call(type, path, data)
rescue DatabaseException => e
  sleep(1.seconds)
  api_call(type, path, data)
end

#reset_tokenObject



78
79
80
# File 'lib/brightpearl_api/client.rb', line 78

def reset_token
  @@token = false
end