-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathabstract_api.rb
105 lines (86 loc) · 2.76 KB
/
abstract_api.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
73
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
100
101
102
103
104
105
module Beyonic::AbstractApi
class ApiError < StandardError
end
module ClassMethods
def set_endpoint_resource(resource)
@endpoint_url = Beyonic.endpoint_base + resource
end
def create(payload = {}, header_overrides = {})
# transform metadata from hash notation to dot notation
if (payload.has_key?:metadata) && (!payload[:metadata].empty?)
payload[:metadata].each do |key, value|
payload["metadata.#{key}"] = value
end
payload.delete:metadata
end
resp = RestClient.post(@endpoint_url, payload, headers(header_overrides))
self.new(Oj.load(resp))
rescue RestClient::BadRequest => e
raise ApiError.new(Oj.load(e.response.body))
end
def list(payload = {})
# Turn payload into query parameters
require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = payload
resp = RestClient.get(@endpoint_url + '?' + uri.query, headers)
ret = self.new(Oj.load(resp))
ret.results = ret.results.map { |obj_attrs| self.new(obj_attrs)}
return ret
end
def get(id)
resp = RestClient.get("#{@endpoint_url}/#{id}", headers)
self.new(Oj.load(resp))
end
def update(id, payload, header_overrides = {})
resp = RestClient.patch("#{@endpoint_url}/#{id}", payload, headers(header_overrides))
self.new(Oj.load(resp))
rescue RestClient::BadRequest => e
raise ApiError.new(Oj.load(e.response.body))
end
def delete(id)
resp = RestClient.delete("#{@endpoint_url}/#{id}", headers)
return true if resp == ""
end
private
def headers(header_overrides = {})
headers_hash = {}
headers_hash.merge!({"Authorization" => "Token #{Beyonic.api_key}"}) if Beyonic.api_key
headers_hash.merge!({"Beyonic-Version" => Beyonic.api_version}) if Beyonic.api_version
headers_hash.merge!({"Beyonic-Client" => "Ruby"})
headers_hash.merge!({"Beyonic-Client-Version" => Beyonic::VERSION})
headers_hash.merge!(header_overrides)
headers_hash
end
end
module InstanceMethods
def save
if respond_to?(:id) && !id.nil?
self.class.update(id, to_h)
else
self.class.create(to_h)
end
end
def []=(name, value)
if name.to_sym == :id
self.id=(value)
else
super(name,value)
end
end
end
module Initializer
def initialize(*args)
super(*args)
#We should define it after Object initialization
define_singleton_method(:id=) do |val|
raise "Can't change id of existing #{self.class}"
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
receiver.send :prepend, Initializer
end
end