Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
uoy-faculty-sinatra-aws / lib / sinatra / lambda_handler.rb
Size: Mime:
# frozen_string_literal: true

require 'logger'
require 'serverless_rack'

LOGGER = Logger.new $stdout

module Sinatra
  # Helpers for production - using AWS Cognito
  module LambdaHandler
    module_function

    def handler(event:, context:, multi_value_headers: nil) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
      # The new handle_request function deals with multi_value_headers automatically, so we can deprecate the argument
      warn '`multi_value_headers` passed to `handler` is deprecated' unless multi_value_headers.nil?

      # Ideally we'd just call handle_request, but we want to generate the log in the middle of the logic
      return {} if keepalive_event?(event)

      env = build_environ(
        event: event,
        context: context,
        headers: parse_headers(event),
        body: parse_body(event)
      )

      status, headers, body = $app.call env # rubocop:disable Style/GlobalVars

      apache_log env, status, headers
      headers.delete 'X-Username'

      format_response(
        event: event,
        status: status,
        headers: headers,
        body: body,
        text_mime_types: TEXT_MIME_TYPES + config['text_mime_types'].to_a
      )
    rescue Exception => e # rubocop:disable Lint/RescueException
      # If there is _any_ exception, we return a 500 error with an error message
      response = {
        'statusCode' => 500,
        'body' => e.message
      }

      LOGGER.fatal response
      LOGGER.fatal e.backtrace.join("\n\t") if e.backtrace

      response
    end

    def apache_log(env, status, headers) # rubocop:disable Metrics/AbcSize
      username = headers.fetch('X-Username')

      request = "#{env['REQUEST_METHOD']} #{env['PATH_INFO']}"
      request = "#{request}?#{env['QUERY_STRING']}" if env['QUERY_STRING'] != ''

      LOGGER.info(
        [
          env['HTTP_X_FORWARDED_FOR'], nil, username, request.inspect, status, headers.fetch('Content-Length'),
          env['HTTP_REFERER'].inspect, env['HTTP_USER_AGENT'].inspect
        ].map { |field| field.nil? || field == '' ? '-' : field }.join(' ')
      )
    end
  end
end