Module: AwsApiGatewayEventHandler

Defined in:
lib/modulator/lambda_handler.rb

Constant Summary collapse

NUMBER_REGEX =
/\A[+-]?\d+(\.[\d]+)?\z/

Class Method Summary collapse

Class Method Details

.call(event:, context:) ⇒ Object



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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/modulator/lambda_handler.rb', line 19

def call(event:, context:)
  wrapper_params = {}

  if ENV['wrapper_name']
    # module init
    require Pathname.getwd.join(ENV['wrapper_path']).to_s
    wrapper = Object.const_get(ENV['wrapper_name'])
    mod_method = ENV['wrapper_method']

    # check arity
    if wrapper.method(mod_method).parameters != [[:keyreq, :event], [:keyreq, :context]]
      raise("#{wrapper}.#{mod_method} should accept event and context keyword arguments")
    end

    # print call info
    puts "Calling wrapper #{wrapper}.#{mod_method}"
    wrapper_result = wrapper.send(mod_method, event: event, context: context)

    if wrapper_result.is_a?(Hash)
      # block with custom status and body
      return {
        statusCode: wrapper_result[:status],
        body: JSON.generate(wrapper_result[:body])
      } if wrapper_result[:status]

      # or set params
      wrapper_params = wrapper_result

    elsif !wrapper_result
      # block if result is false/nil
      return {
        statusCode: 403,
        body: JSON.generate(forbidden: "#{wrapper}.#{mod_method}")
      } if !wrapper_result
    end
  end

  # module init
  require Pathname.getwd.join(ENV['module_path']).to_s
  mod = Object.const_get(ENV['module_name'])
  mod_method = ENV['module_method']

  # gateway def
  verb = ENV['gateway_verb']
  path = ENV['gateway_path']

  # print call info
  method_signature = mod.method(mod_method).parameters
  puts "Resolving #{verb.to_s.upcase} #{path} to #{mod}.#{mod_method} with #{method_signature}"

  # cast path parameters to numbers
  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

  # merge wrapper params
  path_params.merge!(wrapper_params)

  # call the module method
  result =
  if ['GET', 'DELETE'].include?(verb)
    mod.send(mod_method, *path_params.values)

  elsif verb == 'POST'
    payload = JSON.parse(event['body'], symbolize_names: true)
    method_signature.each do |arg_type, arg_name|         # [[:req, :id], [:key, :pet]]
      payload = {arg_name => payload} if arg_type == :key # scope payload to first named argument
    end

    # we can override GET to POST without payload, ruby will break if **payload is resolved from {}
    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

  # set status and body values
  if result.nil?
    status  = 404
    body    = nil # it will print json null string
  else
    status  = result[:status] ? result[:status] : 200
    body    = result[:body] ? result[:body] : result
  end

  # return result
  return {statusCode: status, body: JSON.generate(body)}

  # print and return error
  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