Class: Hyperdrive::Middleware::ParseJSONBody

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperdrive/middleware/parse_json_body.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ParseJSONBody

Returns a new instance of ParseJSONBody.



6
7
8
# File 'lib/hyperdrive/middleware/parse_json_body.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/hyperdrive/middleware/parse_json_body.rb', line 10

def call(env)
  req = Rack::Request.new(env)
  if req.media_type =~ /json$/
    begin
      json_body = MultiJson.load(env['rack.input'].read)
      env["rack.input"].rewind
    rescue => e
      puts "JSONParseError: #{e.message}"
      raise Hyperdrive::Errors::JSONParseError.new
    end
    env['rack.request.form_hash'] ||= {}
    env['rack.request.form_hash'].merge!(json_body)
    env['rack.request.form_input'] = Rack::Utils.build_query(env['rack.request.form_hash'])
    env['rack.input'] = env['rack.request.form_input']
  end
  @app.call(env)
end