kit_rs/http/
request.rs

1use super::ParamError;
2use std::collections::HashMap;
3
4/// HTTP Request wrapper providing Laravel-like access to request data
5pub struct Request {
6    inner: hyper::Request<hyper::body::Incoming>,
7    params: HashMap<String, String>,
8}
9
10impl Request {
11    pub fn new(inner: hyper::Request<hyper::body::Incoming>) -> Self {
12        Self {
13            inner,
14            params: HashMap::new(),
15        }
16    }
17
18    pub fn with_params(mut self, params: HashMap<String, String>) -> Self {
19        self.params = params;
20        self
21    }
22
23    /// Get the request method
24    pub fn method(&self) -> &hyper::Method {
25        self.inner.method()
26    }
27
28    /// Get the request path
29    pub fn path(&self) -> &str {
30        self.inner.uri().path()
31    }
32
33    /// Get a route parameter by name (e.g., /users/{id})
34    /// Returns Err(ParamError) if the parameter is missing, enabling use of `?` operator
35    pub fn param(&self, name: &str) -> Result<&str, ParamError> {
36        self.params
37            .get(name)
38            .map(|s| s.as_str())
39            .ok_or_else(|| ParamError {
40                param_name: name.to_string(),
41            })
42    }
43
44    /// Get all route parameters
45    pub fn params(&self) -> &HashMap<String, String> {
46        &self.params
47    }
48
49    /// Get the inner hyper request
50    pub fn inner(&self) -> &hyper::Request<hyper::body::Incoming> {
51        &self.inner
52    }
53
54    /// Get a header value by name
55    pub fn header(&self, name: &str) -> Option<&str> {
56        self.inner
57            .headers()
58            .get(name)
59            .and_then(|v| v.to_str().ok())
60    }
61
62    /// Check if this is an Inertia XHR request
63    pub fn is_inertia(&self) -> bool {
64        self.header("X-Inertia")
65            .map(|v| v == "true")
66            .unwrap_or(false)
67    }
68
69    /// Get the Inertia version from request headers
70    pub fn inertia_version(&self) -> Option<&str> {
71        self.header("X-Inertia-Version")
72    }
73
74    /// Get partial component name for partial reloads
75    pub fn inertia_partial_component(&self) -> Option<&str> {
76        self.header("X-Inertia-Partial-Component")
77    }
78
79    /// Get partial data keys for partial reloads
80    pub fn inertia_partial_data(&self) -> Option<Vec<&str>> {
81        self.header("X-Inertia-Partial-Data")
82            .map(|v| v.split(',').collect())
83    }
84}