Sha256: 6ea8e341e42397ae4c0c1eabc98a90ed023c2bac251f091e9c9cb68f8f5b586c

Contents?: true

Size: 1.83 KB

Versions: 2

Compression:

Stored size: 1.83 KB

Contents

module AppManager
  module Actions
    class ApiCacheHandler
      def initialize
        
      end


      def around(controller)
        init(controller)
        if should_response_cache?
          log_info
          render_cached_response
        else
          yield
          @response_cache.write_cache(controller.response) if @request.get?
        end
      end

      protected

      def should_response_cache?
       return @request.get? && @response_cache.cached_response.present?
      end

      def log_info
        # processor       = "#{@controller.class.name}##{@controller.action_name}".blue
        # responder       = Rainbow('API Response Cache').green
        Rails.logger.info "=== #{@controller.class.name}##{@controller.action_name} response by App Manager Response Cache ==="
      end

      def init(controller)
        @controller         = controller
        @request            = controller.request
        @response_cache     = ResponseCache.new(cache_path)
      end

      def cache_path
        @cache_path = "app-manager-cache"

        path_only   = @request.fullpath.split('?').first
        @cache_path = "#{@cache_path}#{path_only}"

        if AppManager.configuration.cache_by_headers.present?
          headers = AppManager.configuration.cache_by_headers.map do |header|
            @request.headers[header].to_s
          end
          headers_cache_path = headers.join('-')
          @cache_path = "#{@cache_path}/#{headers_cache_path}"
        end

        @cache_path
      end

      def render_cached_response
        body    = @response_cache.body
        status  = @response_cache.status
        headers = @response_cache.headers
        # headers.try(:each) do |key, value|
        #   @controller.response.headers[key] = value
        # end
        @controller.render json: body, status: status 
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
app_manager-1.1.0 lib/app_manager/api_cache_handler.rb
app_manager-1.0.3 lib/app_manager/api_cache_handler.rb