Sha256: 001bf5773f050b1bdfd48cc75f9622684df19dbe20a51a2adb19e6d69173c636

Contents?: true

Size: 748 Bytes

Versions: 3

Compression:

Stored size: 748 Bytes

Contents

require "json"

module Tynn::JSONParser
  def self.setup(app) # :nodoc:
    app.use(Tynn::JSONParser::Middleware)
  end

  class Middleware # :nodoc:
    CONTENT_TYPE = "application/json".freeze
    FORM_HASH = "rack.request.form_hash".freeze
    FORM_INPUT = "rack.request.form_input".freeze

    def initialize(app)
      @app = app
    end

    def call(env)
      request = Rack::Request.new(env)

      if json?(request) && !(body = request.body.read).empty?
        request.body.rewind

        request.env[FORM_HASH] = JSON.parse(body)
        request.env[FORM_INPUT] = request.body
      end

      return @app.call(request.env)
    end

    private

    def json?(request)
      return request.media_type == CONTENT_TYPE
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tynn-1.0.0.rc1 lib/tynn/json_parser.rb
tynn-0.0.4 lib/tynn/json_parser.rb
tynn-0.0.3 lib/tynn/json_parser.rb