Class: Rack::PostBodyContentTypeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/contrib/post_body_content_type_parser.rb

Overview

A Rack middleware for parsing POST/PUT body data when Content-Type is not one of the standard supported types, like application/json.

TODO: Find a better name.

Constant Summary collapse

CONTENT_TYPE =

Constants

'CONTENT_TYPE'.freeze
POST_BODY =
'rack.input'.freeze
FORM_INPUT =
'rack.request.form_input'.freeze
FORM_HASH =
'rack.request.form_hash'.freeze
APPLICATION_JSON =

Supported Content-Types

'application/json'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ PostBodyContentTypeParser

Returns a new instance of PostBodyContentTypeParser.



27
28
29
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 27

def initialize(app)
  @app = app
end

Instance Method Details

#bad_request(body = 'Bad Request') ⇒ Object



41
42
43
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 41

def bad_request(body = 'Bad Request')
  [ 400, { 'Content-Type' => 'text/plain', 'Content-Length' => body.size.to_s }, [body] ]
end

#call(env) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 31

def call(env)
  if Rack::Request.new(env).media_type == APPLICATION_JSON && (body = env[POST_BODY].read).length != 0
    env[POST_BODY].rewind # somebody might try to read this stream
    env.update(FORM_HASH => JSON.parse(body, :create_additions => false), FORM_INPUT => env[POST_BODY])
  end
  @app.call(env)
rescue JSON::ParserError
  bad_request('failed to parse body as JSON')
end