Class: Guaraci::Request

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

Overview

Represents the requests wrapper that provides convenient access to request data. This class wraps the HTTP request object from Async::HTTP.

Examples:

Basic request information

request.method        #=> "GET"
request.path_segments #=> ["api", "users", "123"]
request.headers       #=> Protocol::HTTP::Headers instance

Accessing request data

request.params       #=> {"name" => "John", "email" => "[email protected]"}
request.query_params #=> [["sort", "name"], ["order", "asc"]]

See Also:

Author:

  • Guilherme Silva

Since:

  • 1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_request) ⇒ Request

Initialize a new request wrapper.

Creates a new Request instance that wraps the underlying HTTP request object. Automatically extracts commonly needed information like HTTP method and path segments for easy access and pattern matching.

Examples:

# Usually called internally by the server
request = Guaraci::Request.new(async_http_request)

Since:

  • 1.0.0



77
78
79
80
81
# File 'lib/guaraci/request.rb', line 77

def initialize(raw_request)
  @method = raw_request.method
  @path_segments = raw_request.path&.split("/")&.reject(&:empty?)
  @raw_request = raw_request
end

Instance Attribute Details

#methodString (readonly)

The HTTP method for this request.

Common methods include GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS. The method is automatically extracted from the underlying request object and normalized to uppercase string format.

Examples:

request.method #=> "GET"

Since:

  • 1.0.0



30
31
32
# File 'lib/guaraci/request.rb', line 30

def method
  @method
end

#path_segmentsArray<String> (readonly)

The path segments extracted from the request URL.

The path is automatically split by “/” and empty segments are removed. This creates an array that’s perfect for pattern matching and routing logic. Leading and trailing slashes are ignored.

Examples:

Path segments

# For URL: /api/users/123/profile
request.path_segments #=> ["api", "users", "123", "profile"]
user_id = request.path_segments[2]  #=> "123"

Pattern Matching for Routing (Recommended)

# Using Ruby's pattern matching for elegant routing
case [request.method, request.path_segments]
in ['GET', ['api', 'users', user_id]]
  # user_id automatically captured from URL
in ['GET', ['api', 'posts', post_id, 'comments']]
  # post_id automatically captured from URL
end

Since:

  • 1.0.0



52
53
54
# File 'lib/guaraci/request.rb', line 52

def path_segments
  @path_segments
end

#raw_requestObject (readonly)

The original request object from the HTTP server.

This provides access to the underlying request implementation when you need low-level access to request data that isn’t exposed through the wrapper methods. Use this when you need to access protocol-specific features.

Examples:

request.raw_request.version #=> "HTTP/1.1"
request.raw_request.scheme  #=> "http"

See Also:

Since:

  • 1.0.0



65
66
67
# File 'lib/guaraci/request.rb', line 65

def raw_request
  @raw_request
end

Instance Method Details

#bodyString?

Read and return the request body content. Returns nil if the request has no body content.

Examples:

request.body #=> '{"name":"John","email":"[email protected]"}'

For requests without body

request.body #=> nil

Since:

  • 1.0.0



91
92
93
# File 'lib/guaraci/request.rb', line 91

def body
  @body ||= raw_request&.read
end

#headersProtocol::HTTP::Headers

Access the request headers.

All headers are accessed in lowercase strings according to Protocol::HTTP::Headers So that way, “User-Agent” becomes “user-agent”

Examples:

request.headers['content-type']   #=> 'application/json'
request.headers['authorization']  #=> 'Bearer token123'
request.headers['user-agent']     #=> 'Mozilla/5.0...'

See Also:

Since:

  • 1.0.0



131
# File 'lib/guaraci/request.rb', line 131

def headers = raw_request.headers

#paramsHash

Parse the request body as JSON and return the resulting object.

Attempts to parse the request body as JSON using JSON.parse. If the body is not valid JSON or is empty, returns an empty hash instead of raising an exception. This makes it safe to call even when you’re not sure if the request contains JSON data.

Examples:

Successful parsing

# Request body: '{"name":"John","age":30}'
request.params #=> {"name" => "John", "age" => 30}

Invalid JSON handling

# Request body: 'invalid json'
request.params #=> {}

Empty body handling

# Request body: nil
request.params #=> {}

See Also:

  • JSON.parse

Since:

  • 1.0.0



115
116
117
118
119
# File 'lib/guaraci/request.rb', line 115

def params
  JSON.parse(body)
rescue JSON::ParserError
  {}
end

#queryString

Extract the query string from the request URL.

Returns the complete query string portion of the URL (everything after the “?”). If no query string is present, returns an empty string. The query string is returned as-is without any URL decoding.

Examples:

# For URL: /users?name=john&age=30&active=true
request.query #=> "name=john&age=30&active=true"

No query string

# For URL: /users
request.query #=> ""

Since:

  • 1.0.0



147
148
149
# File 'lib/guaraci/request.rb', line 147

def query
  raw_request&.query || ""
end

#query_paramsArray<Array<String>>

Parse the query string into key-value pairs.

Splits the query string into an array of [key, value] pairs for easy processing. Each parameter is split on the “=” character. Parameters without values will have the value portion as an empty string or nil. The result is cached for subsequent calls.

Examples:

# For query: "name=john&age=30&active=true"
request.query_params #=> [["name", "john"], ["age", "30"], ["active", "true"]]

Parameters without values

# For query: "debug&verbose=1&flag"
request.query_params #=> [["debug"], ["verbose", "1"], ["flag"]]

No query string

request.query_params #=> []

Since:

  • 1.0.0



169
170
171
# File 'lib/guaraci/request.rb', line 169

def query_params
  @query_params ||= parse_query
end