Sha256: 51e0087fb5742d2f8f4af61e7d87103e1eeead18d34ff951236ab4c0b4f32f3a

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

require 'active_support/core_ext/object/inclusion'
require 'sparrow/middleware'
require 'sparrow/strategies/json_format_strategies/json_format_strategy'

module Sparrow
  class ResponseMiddleware < Middleware
    def call(env)
      @last_env                = env
      @status, @headers, @body = @app.call(env)
      [status, headers, converted_response_body]
    end

    def converted_response_body
      response_body = Sparrow::Strategies::JsonFormatStrategy.convert(body)

      # just pass the response if something went wrong inside the application
      return response_body if unprocessable_status?

      if response_body.present?
        response_strategy = strategy.new(last_env, :response, response_body)
        response_strategy.handle

        if response_body.is_a?(Array) then
          response_body
        else
          Array(response_strategy.json_body)
        end
      else
        []
      end
    end

    def unprocessable_status?
      @status.in?(500..511) || @status == 404
    end

    def content_type
      headers['Content-Type'].split(';').first #||
          # last_env['CONTENT-TYPE'] ||
          # last_env['Content-Type'] ||
          # last_env['CONTENT_TYPE']
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cp-sparrow-0.0.12 lib/sparrow/response_middleware.rb