Skip to content

Instantly share code, notes, and snippets.

@a-bx
Last active May 15, 2019 19:19
Show Gist options
  • Save a-bx/8a4f6eac22320e95d35ce624e7905252 to your computer and use it in GitHub Desktop.
Save a-bx/8a4f6eac22320e95d35ce624e7905252 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'sinatra/base'
require 'active_support/core_ext/string'
require 'dotenv/load'
# My rack lambda facade application ohh yeah
class App < Sinatra::Base
def self.parse_route(route_key)
method, route = route_key.split('-')
route = route.gsub(/{([_0-9a-z\+]+)}/, ':\1')
route = route.gsub(':cors+', '*')
[method.upcase, route]
end
helpers do
def request_headers
# rubocop:disable EachWithObject
env.inject({}) do |acc, (k, v)|
# rubocop:disable PerlBackrefs
acc[$1.downcase.tr('_', '-')] = v if k =~ /^http_(.*)/i
# rubocop:enable PerlBackrefs
acc
end
# rubocop:enable EachWithObject
end
def parse_event(route_key)
method, route = route_key.split('-')
method = method.upcase
path = env['REQUEST_PATH']
{
'resource' => route, 'path' => path, 'httpMethod' => method,
'headers' => request_headers, 'pathParameters' => {},
'queryStringParameters' => params, 'requestContext' => {
'resourcePath' => route, 'httpMethod' => method, 'path' => path
}, 'body' => request.body.read.force_encoding('utf-8')
}
end
end
Dir['./app/requests/*.rb'].each do |file|
name = File.basename(file, '.*')
require file
class_name = "Requests::#{name.camelize}"
route_class = class_name.constantize
route_class.routes.each do |route_key, _value|
method, path = parse_route(route_key)
puts " Registring #{method} #{path}"
send(method.downcase.to_sym, path) do
event = parse_event(route_key)
response = route_class.handler(event: event, context: nil)
content_type :json
headers \
response[:headers].stringify_keys
status response[:statusCode]
body response[:body]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment