-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathendpoint.rb
96 lines (83 loc) · 2.91 KB
/
endpoint.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
module Seahorse
module Client
module Plugins
# @seahorse.client.option [String] :endpoint
# The HTTP or HTTPS endpoint to send requests to.
# For example:
#
# 'example.com'
# 'http://example.com'
# 'https://example.com'
# 'http://example.com:123'
#
# This must include the host. It may also include the scheme and
# port. When the scheme is not set it defaults to `https`.
#
class Endpoint < Plugin
option(:endpoint)
def after_initialize(client)
endpoint = URI.parse(client.config.endpoint.to_s)
if URI::HTTPS === endpoint or URI::HTTP === endpoint
client.config.endpoint = endpoint
else
msg = 'expected :endpoint to be a HTTP or HTTPS endpoint'
raise ArgumentError, msg
end
end
class Handler < Client::Handler
def call(context)
context.http_request.endpoint = build_endpoint(context)
@handler.call(context)
end
private
def build_endpoint(context)
uri = URI.parse(context.config.endpoint.to_s)
apply_path_params(uri, context)
apply_querystring_params(uri, context)
uri
end
def apply_path_params(uri, context)
path = uri.path.sub(/\/$/, '')
path += context.operation.http_request_uri.split('?')[0]
input = context.operation.input
uri.path = path.gsub(/{\w+\+?}/) do |placeholder|
if placeholder.include?('+')
placeholder = placeholder[1..-3]
greedy = true
else
placeholder = placeholder[1..-2]
end
name, shape = input.member_by_location_name(placeholder)
param = context.params[name]
if greedy
param.split('/').map{ |value| escape(value) }.join('/')
else
escape(param)
end
end
end
def apply_querystring_params(uri, context)
parts = []
parts << context.operation.http_request_uri.split('?')[1]
parts.compact!
if input = context.operation.input
params = context.params
input.members.each do |member_name, member|
if member.location == 'querystring' && !params[member_name].nil?
param_name = member.location_name
param_value = params[member_name]
parts << "#{param_name}=#{escape(param_value.to_s)}"
end
end
end
uri.query = parts.empty? ? nil : parts.join('&')
end
def escape(string)
Util.uri_escape(string)
end
end
handle(Handler, priority: 90)
end
end
end
end