class Rack::Shelf::ResponseAdapter

Transforms a standard Rack response array to a return value required by AWS Lambda. @see docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

Public Class Methods

convert(response) click to toggle source

Converts a Rack response to one supported by AWS Lambda. @param response [Array] Three-element array.

This is the standard response from a Rack application.
Must have the elements: status code, headers, and body.

@return [Hash] AWS Lambda response. @see www.rubydoc.info/github/rack/rack/file/SPEC#label-The+Response

# File lib/rack/shelf/response_adapter.rb, line 15
def self.convert(response)
  new(*response).build
end
error(exception, status_code = 500) click to toggle source

Generates a Lambda response for an error. @param exception [Exception, to_s] Caught exception. @param status_code [Integer] HTTP response code. @return [Hash] AWS Lambda response.

# File lib/rack/shelf/response_adapter.rb, line 23
def self.error(exception, status_code = 500)
  new(status_code, {}, exception.to_s).build
end
new(status_code, headers, body) click to toggle source

Creates an adapter dedicated to processing one response. @param status_code [#to_i] HTTP status code. @param headers [#each] HTTP headers. @param body [#each] Response body.

# File lib/rack/shelf/response_adapter.rb, line 31
def initialize(status_code, headers, body)
  @status_code = status_code
  @headers     = headers
  @body        = body
end

Public Instance Methods

build() click to toggle source

Constructs the AWS Lambda response. @return [Hash]

# File lib/rack/shelf/response_adapter.rb, line 39
def build
  {
    'status_code' => status_code,
    'headers' => headers,
    'body' => body,
    'isBase64Encoded' => false
  }
end

Private Instance Methods

body() click to toggle source

Constructs the response body. @return [String]

# File lib/rack/shelf/response_adapter.rb, line 70
def body
  StringIO.new.tap do |io|
    @body.each do |part|
      io.write(part)
    end
    @body.close if @body.respond_to?(:close)
  end.string
end
headers() click to toggle source

Constructs the HTTP headers. @return [Hash]

# File lib/rack/shelf/response_adapter.rb, line 58
def headers
  # Typically, the headers are already a hash.
  # But, the Rack Spec only requires the object to expose `#each`.
  {}.tap do |hash|
    @headers.each do |key, value|
      hash[key] = value
    end
  end
end
status_code() click to toggle source

The integer HTTP status code. @return [Integer]

# File lib/rack/shelf/response_adapter.rb, line 52
def status_code
  @status_code.to_i
end