Class: Rubino::API::Request

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

Overview

Operation-facing view over the Rack env: URL captures, parsed JSON body, query string, headers, and a dry-schema validation helper.

Body comes from env (set by JsonParser middleware), so operations never touch rack.input directly.

request.params              # URL captures (e.g. { "id" => "abc" })
request.body                # parsed JSON body (Hash)
request.validate!(schema)   # runs dry-schema, raises ValidationError on fail
request.header("X-Foo")     # case-insensitive header lookup

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, params) ⇒ Request

Returns a new instance of Request.

Parameters:

  • env (Hash)

    Rack env

  • params (Hash{String=>String})

    captures from the matched route



18
19
20
21
# File 'lib/rubino/api/request.rb', line 18

def initialize(env, params)
  @env = env
  @params = params
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



23
24
25
# File 'lib/rubino/api/request.rb', line 23

def env
  @env
end

#paramsObject (readonly)

Returns the value of attribute params.



23
24
25
# File 'lib/rubino/api/request.rb', line 23

def params
  @params
end

Instance Method Details

#bodyHash

Returns parsed JSON body, or {} when none.

Returns:

  • (Hash)

    parsed JSON body, or {} when none



26
27
28
# File 'lib/rubino/api/request.rb', line 26

def body
  @env.fetch("rubino.json", {})
end

#header(name) ⇒ Object

Case-insensitive header lookup; “X-Foo” becomes HTTP_X_FOO.



31
32
33
34
# File 'lib/rubino/api/request.rb', line 31

def header(name)
  key = "HTTP_#{name.upcase.tr("-", "_")}"
  @env[key]
end

#queryObject



36
37
38
# File 'lib/rubino/api/request.rb', line 36

def query
  @query ||= Rack::Utils.parse_nested_query(@env["QUERY_STRING"].to_s)
end

#validate!(schema) ⇒ Hash

Runs the body through a dry-schema and returns the coerced hash. dry-schema is used only at the HTTP boundary; internals trust their types.

Parameters:

  • schema (Dry::Schema::Processor)

Returns:

  • (Hash)

    coerced, validated payload

Raises:

  • (ValidationError)

    when the schema rejects the body (mapped to 422 by ErrorHandler)



46
47
48
49
50
51
# File 'lib/rubino/api/request.rb', line 46

def validate!(schema)
  result = schema.call(body)
  raise ValidationError.new("invalid request body", details: { errors: result.errors.to_h }) if result.failure?

  result.to_h
end