Class: Jersey::Middleware::AutoJson

Inherits:
Object
  • Object
show all
Defined in:
lib/jersey/middleware/auto_json.rb

Constant Summary collapse

JSON_PARSER =
lambda { |data| JSON.parse(data) }
JSON_REGEX =
/json/

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ AutoJson

Configure the :porser and the :json_regex though if you’re going to be strict about this you probably shouldn’t be using this middleware



15
16
17
18
19
# File 'lib/jersey/middleware/auto_json.rb', line 15

def initialize(app, options = {})
  @app = app
  @parser = options.delete(:parser) || JSON_PARSER
  @json_regex = options.delete(:json_regex) || JSON_REGEX
end

Instance Method Details

#call(env) ⇒ Object

Make json happen.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/jersey/middleware/auto_json.rb', line 22

def call(env)
  req = Rack::Request.new(env)
  type = req.media_type
  if type && type.match(@json_regex)
    # raise error if parsing declared json
    begin
      env['rack.json'] = @parser.call(req.body.read)
    rescue => ex
      raise BadRequest, "json parse error in AutoJson: #{ex.message}"
    end
  elsif ["{","["].include?(req.body.read(1))
    # make best effort to parse what looks like json
    req.body.rewind
    env['rack.json'] = @parser.call(req.body.read) rescue nil
  end
  req.body.rewind
  @app.call(env)
end