Sha256: 556917cce43a4c32d1d9970d8b7018a84bc0260a46a70af8291d3f66d0a06be8

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

require 'rack'

module ApiProxy
  class ResponseBuilder
    attr_reader :env, :namespace, :config

    def initialize(env, namespace = :default)
      @env = env
      @namespace = namespace
      @config = ApiProxy.configuration(namespace)
    end

    def allow_request?
      return false unless request.path.start_with?(config.request_starts_with)

      config.request_allowed.call(@env)
    end

    def response
      Rack::Response.new(
        result.to_s,
        result.code,
        ApiProxy::HeadersFilter.new(result.headers).filter
      )
    end

    private

    def request
      @request ||= Rack::Request.new(env)
    end

    def result
      @result ||= ApiProxy::SignedRequest.new(request.request_method, url, options).perform
    end

    def url
      path = request.path.gsub(config.request_starts_with, '')
      File.join(config.api_url.to_s, path)
    end

    def options
      { namespace: namespace, body: filtered_params, headers: headers }
    end

    def filtered_params
      params.reject { |key, _value| config.reject_params.include?(key.to_s) }
    end

    def params
      @params ||= (env['action_dispatch.request.request_parameters'].presence || request.params)
    end

    def headers
      config.custom_headers.call(env)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
api_proxy-0.2.7 lib/api_proxy/response_builder.rb
api_proxy-0.2.6 lib/api_proxy/response_builder.rb
api_proxy-0.2.5 lib/api_proxy/response_builder.rb