Sha256: 44e9eaedcdea2f286d6ab995bd4973bc9722c1b51bec723c904c42f2e4a628b6

Contents?: true

Size: 1.49 KB

Versions: 4

Compression:

Stored size: 1.49 KB

Contents

require 'rack/utils'

module Flipper
  module Api
    class JsonParams
      include Rack::Utils

      def initialize(app)
        @app = app
      end

      CONTENT_TYPE = 'CONTENT_TYPE'.freeze
      QUERY_STRING = 'QUERY_STRING'.freeze
      REQUEST_BODY = 'rack.input'.freeze
      REWIND_BODY = Gem::Version.new(Rack.release) < Gem::Version.new('3.0.0')

      # Public: Merge request body params with query string params
      # This way can access all params with Rack::Request#params
      # Rack does not add application/json params to Rack::Request#params
      # Allows app to handle x-www-url-form-encoded / application/json request
      # parameters the same way
      def call(env)
        if env[CONTENT_TYPE] == 'application/json'
          body = env[REQUEST_BODY].read
          env[REQUEST_BODY].rewind if REWIND_BODY
          update_params(env, body)
        end
        @app.call(env)
      end

      private

      # Rails 3.2.2.1 Rack version does not have Rack::Request#update_param
      # Rack 1.5.0 adds update_param
      # This method accomplishes similar functionality
      def update_params(env, data)
        return if data.empty?
        parsed_request_body = Typecast.from_json(data)
        env["parsed_request_body".freeze] = parsed_request_body
        parsed_query_string = parse_query(env[QUERY_STRING])
        parsed_query_string.merge!(parsed_request_body)
        parameters = build_query(parsed_query_string)
        env[QUERY_STRING] = parameters
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
flipper-api-1.3.2 lib/flipper/api/json_params.rb
flipper-api-1.3.1 lib/flipper/api/json_params.rb
flipper-api-1.3.0 lib/flipper/api/json_params.rb
flipper-api-1.3.0.pre lib/flipper/api/json_params.rb