Class: Rack::PostBodyContentTypeParser

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

Overview

DEPRECATED: JSONBodyParser is a drop-in replacement that is faster and more configurable.

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

How to use the middleware

Example of simple config.ru file:

require 'rack'
require 'rack/contrib'

use ::Rack::PostBodyContentTypeParser

app = lambda do |env|
  request = Rack::Request.new(env)
  body = "Hello #{request.params['name']}"
  [200, {'Content-Type' => 'text/plain'}, [body]]
end

run app

Example with passing block argument:

use ::Rack::PostBodyContentTypeParser do |body|
  { 'params' => JSON.parse(body) }
end

Example with passing proc argument:

parser = ->(body) { { 'params' => JSON.parse(body) } }
use ::Rack::PostBodyContentTypeParser, &parser

Failed JSON parsing

Returns “400 Bad request” response if invalid JSON document was sent:

Raw HTTP response:

HTTP/1.1 400 Bad Request
Content-Type: text/plain
Content-Length: 28

failed to parse body as JSON

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, &block) ⇒ PostBodyContentTypeParser

Returns a new instance of PostBodyContentTypeParser.



68
69
70
71
72
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 68

def initialize(app, &block)
  warn "[DEPRECATION] `PostBodyContentTypeParser` is deprecated. Use `JSONBodyParser` as a drop-in replacement."
  @app = app
  @block = block || Proc.new { |body| JSON.parse(body, :create_additions => false) }
end

Instance Method Details

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



84
85
86
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 84

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

#call(env) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/rack/contrib/post_body_content_type_parser.rb', line 74

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 => @block.call(body), FORM_INPUT => env[POST_BODY])
  end
  @app.call(env)
rescue JSON::ParserError
  bad_request('failed to parse body as JSON')
end