Class: KB::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url, api_key: ENV['KB_API_KEY']) ⇒ Client

Returns a new instance of Client.



5
6
7
8
# File 'lib/kb/client.rb', line 5

def initialize(base_url, api_key: ENV['KB_API_KEY'])
  @api_key = api_key
  @base_url = base_url
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



3
4
5
# File 'lib/kb/client.rb', line 3

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



3
4
5
# File 'lib/kb/client.rb', line 3

def base_url
  @base_url
end

Instance Method Details

#all(filters = {}) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/kb/client.rb', line 19

def all(filters = {})
  cache_key = "#{@base_url}/#{filters.sort.to_h}"

  KB::Cache.fetch(cache_key) do
    connection.get('', attributes_case_transform(filters)).body
  end
end

#clear_cache_for(key) ⇒ Object



53
54
55
# File 'lib/kb/client.rb', line 53

def clear_cache_for(key)
  KB::Cache.delete("#{@base_url}/#{key}")
end

#create(attributes) ⇒ Object



35
36
37
# File 'lib/kb/client.rb', line 35

def create(attributes)
  connection.post('', attributes_to_json(attributes)).body
end

#destroy(key) ⇒ Object



44
45
46
47
# File 'lib/kb/client.rb', line 44

def destroy(key)
  clear_cache_for(key)
  connection.delete(key.to_s).body
end

#find(key, params = {}) ⇒ Object

Raises:

  • (Faraday::ResourceNotFound)


27
28
29
30
31
32
33
# File 'lib/kb/client.rb', line 27

def find(key, params = {})
  raise Faraday::ResourceNotFound, {} if key.blank?

  KB::Cache.fetch("#{@base_url}/#{key}") do
    connection.get(key, attributes_case_transform(params)).body
  end
end

#request(sub_path, filters: nil, method: :get) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/kb/client.rb', line 10

def request(sub_path, filters: nil, method: :get)
  return connection.public_send(method, sub_path, attributes_to_json(filters)).body if method != :get

  cache_key = "#{@base_url}/#{sub_path}/#{(filters || {}).sort.to_h}"
  KB::Cache.fetch(cache_key) do
    connection.public_send(method, sub_path, filters).body
  end
end

#update(key, attributes) ⇒ Object



39
40
41
42
# File 'lib/kb/client.rb', line 39

def update(key, attributes)
  clear_cache_for(key)
  connection.patch(key.to_s, attributes_to_json(attributes)).body
end

#upsert(attributes) ⇒ Object



49
50
51
# File 'lib/kb/client.rb', line 49

def upsert(attributes)
  connection.put('', attributes_to_json(attributes)).body
end