-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathrequest_adapter.rb
112 lines (91 loc) · 2.73 KB
/
request_adapter.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
106
107
108
109
110
111
112
module Api
class RequestAdapter
delegate :subject, :subject_id, :collection, :collection_id, :subcollection, :subcollection_id, :subcollection?, :path, :version?, :to => :href
def initialize(req, params)
@request = req
@params = params
end
def to_hash
[:method, :action, :fullpath, :url, :base,
:path, :prefix, :version, :api_prefix,
:collection, :c_suffix, :collection_id, :subcollection, :subcollection_id]
.each_with_object({}) { |attr, hash| hash[attr] = send(attr) }
end
def action
# for basic HTTP POST, default action is "create" with data being the POST body
@action ||= case method
when :get then 'read'
when :put, :patch then 'edit'
when :delete then 'delete'
when :options then 'options'
else json_body['action'] || 'create'
end
end
def api_prefix
@api_prefix ||= "#{base}#{prefix}"
end
def api_suffix
@api_suffix ||= "?provider_class=#{@params['provider_class']}" if @params['provider_class']
end
def attributes
@attributes ||= @params['attributes'].to_s.split(',')
end
def base
url.partition(fullpath)[0] # http://target
end
def c_suffix
@params[:c_suffix]
end
def expand?(what)
expand_requested.include?(what.to_s)
end
def hide?(thing)
@hide ||= @params["hide"].to_s.split(",")
@hide.include?(thing)
end
def json_body
@json_body ||= begin
body = @request.body.read if @request.body
body.blank? || body == "null" ? {} : JSON.parse(body)
end
end
def method
@method ||= @request.request_method.downcase.to_sym # :get, :patch, ...
end
def version
@version ||= if version?
href.version[1..-1] # Switching API Version
else
ManageIQ::Api::VERSION # Default API Version
end
end
def url
@request.url # http://target/api/...
end
def prefix(version = true)
prefix = "/#{path.split('/')[1]}" # /api
return prefix unless version
version? ? "#{prefix}/#{href.version}" : prefix
end
def href
@href ||= Href.new(url)
end
def resources
if json_body.key?("resources")
json_body["resources"]
else
[resource]
end
end
def resource
json_body.fetch("resource", json_body.except("action"))
end
private
def expand_requested
@expand ||= @params['expand'].to_s.split(',')
end
def fullpath
@request.fullpath # /api/...¶m=value...
end
end
end