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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
# File 'lib/lambda/aws_lambda_handler.rb', line 32
def call(event:, context:)
wrapper_params = {}
if ENV['wrapper_name']
require Pathname.getwd.join(ENV['wrapper_path']).to_s
wrapper = Object.const_get(ENV['wrapper_name'])
mod_method = ENV['wrapper_method']
if wrapper.method(mod_method).parameters != [[:keyreq, :event], [:keyreq, :context]]
raise("#{wrapper}.#{mod_method} should accept event and context keyword arguments")
end
puts "Calling wrapper #{wrapper}.#{mod_method}"
wrapper_result = wrapper.send(mod_method, event: event, context: context)
if wrapper_result.is_a?(Hash)
return {
statusCode: wrapper_result[:status],
body: JSON.generate(wrapper_result[:body])
} if wrapper_result[:status]
wrapper_params = wrapper_result
elsif !wrapper_result
return {
statusCode: 403,
body: JSON.generate(forbidden: "#{wrapper}.#{mod_method}")
} if !wrapper_result
end
end
require Pathname.getwd.join(ENV['module_path']).to_s
mod = Object.const_get(ENV['module_name'])
mod_method = ENV['module_method']
verb = ENV['gateway_verb']
path = ENV['gateway_path']
method_signature = mod.method(mod_method).parameters
puts "Resolving #{verb.to_s.upcase} #{path} to #{mod}.#{mod_method} with #{method_signature}"
path_params = event['pathParameters'].each_with_object({}) do |(key, value), params|
if matcher = NUMBER_REGEX.match(value)
value = matcher[1] ? Float(value) : value.to_i
end
params[key] = value
end
path_params.merge!(wrapper_params)
result =
if ['GET', 'DELETE'].include?(verb)
mod.send(mod_method, *path_params.values)
elsif verb == 'POST'
payload = AwsLambdaHandler.symbolize_keys(JSON.parse(event['body']))
method_signature.each do |arg_type, arg_name|
payload = {arg_name => payload} if arg_type == :key
end
if payload.any?
mod.send(mod_method, *path_params.values, **payload)
else
mod.send(mod_method, *path_params.values)
end
else
raise 'Verb should be GET, POST or DELETE'
end
if result.nil?
status = 404
body = nil
else
status = result[:status] ? result[:status] : 200
body = result[:body] ? result[:body] : result
end
return {statusCode: status, body: JSON.generate(body)}
rescue => e
puts output = {
statusCode: 500,
body: JSON.generate(
error: {
class: e.class,
message: e.message
}.merge(ENV['debug'] ? {backtrace: e.backtrace.take(20)} : {})
)
}
output
end
|