Class: Rubino::API::Middleware::JsonParser

Inherits:
Object
  • Object
show all
Defined in:
lib/rubino/api/middleware/json_parser.rb

Overview

Parses JSON request bodies once and stashes the result on env for Request#body to read. Only POST/PUT/PATCH with an application/json content-type are parsed; everything else gets an empty Hash so operations can rely on the key always existing.

Malformed JSON raises ValidationError, which ErrorHandler turns into 422.

Body size is capped at api.max_body_bytes (default 5 MiB). Requests that advertise a larger Content-Length, or whose body turns out to exceed the cap mid-read (i.e. Content-Length lied or was absent), are short-circuited to 413 here — ErrorHandler is bypassed because 413 is not part of the typed-error map.

Constant Summary collapse

APPLICABLE_METHODS =
%w[POST PUT PATCH].freeze
DEFAULT_MAX_BODY_BYTES =
5 * 1024 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JsonParser

Returns a new instance of JsonParser.



24
25
26
# File 'lib/rubino/api/middleware/json_parser.rb', line 24

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubino/api/middleware/json_parser.rb', line 28

def call(env)
  if APPLICABLE_METHODS.include?(env["REQUEST_METHOD"]) && json_content?(env)
    limit = max_body_bytes
    return too_large(limit) if content_length_over_limit?(env, limit)

    body, overflowed = read_capped(env, limit)
    return too_large(limit) if overflowed

    env["rubino.json"] = parse(body)
  else
    env["rubino.json"] = {}
  end
  @app.call(env)
end