Class: Brightpearl::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/brightpearl/client.rb

Class Method Summary collapse

Class Method Details

.base_urlObject



67
68
69
# File 'lib/brightpearl/client.rb', line 67

def self.base_url
  "https://#{Brightpearl.config.api_domain}/public-api/#{Brightpearl.config.}"; 
end

.send_request(path:, method: :get, **options) ⇒ 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
# File 'lib/brightpearl/client.rb', line 14

def self.send_request(path:, method: :get, **options )
  headers = {
    "brightpearl-app-ref": "#{Brightpearl.config.app_ref}",
    "brightpearl-dev-ref": "#{Brightpearl.config.dev_ref}",
    "Authorization": "Bearer #{Brightpearl.config.token}"
  }

  url = "#{base_url}/#{path}"

  case method
  when :get
    response = HTTParty.get(url, headers: headers )
  when :delete
    response = HTTParty.delete(url, headers: headers)
  when :patch
    response = HTTParty.patch(url, 
      headers: headers.merge({ "Content-Type": "application/json" }), 
      body: options[:body].to_json,
    )
  when :put
    response = HTTParty.put(url, 
      headers: headers.merge({ "Content-Type": "application/json" }), 
      body: options[:body].to_json,
    )
  when :post
    response = HTTParty.post(url, 
      headers: headers.merge({ "Content-Type": "application/json" }), 
      body: options[:body].to_json,
    )
  when :options
    response = HTTParty.options(url, headers: headers )
  else
    puts "Unrecognized http method"
  end

  puts url if Brightpearl.config.debug_mode
  json = JSON.parse(response.body)

  if response.code == 503 # Unavailable MOST likeyly throttled
    raise Brightpearl::Throttled.new("Throttled", response: json, status: response.code)
  elsif response.code == 401
    raise Brightpearl::InvalidToken.new(json["response"], response: json, status: 401)
  elsif !!json["errors"]
    raise Brightpearl::RequestError.new("Request Error",  response: json, status: response.code)
  end

  return { 
    payload: json, 
    quota_remaining: response.headers["brightpearl-requests-remaining"] 
  }
  
end

.temp(token:, &block) ⇒ Object

Send a request using a different token than the global config. (Useful when using a different token for specific calls)



4
5
6
7
8
9
10
11
12
# File 'lib/brightpearl/client.rb', line 4

def self.temp(token:, &block)
  original_token = Brightpearl.config.token
  begin
    Brightpearl.config.token = token
    yield
  ensure
    Brightpearl.config.token = original_token
  end
end