elif_http/handlers/
extractors.rs

1//! Request data extractors for handler parameters
2
3use crate::foundation::RequestExtractor;
4use crate::request::ElifRequest;
5use crate::errors::HttpError;
6
7/// Extract query parameters from the request
8pub struct QueryExtractor<T> {
9    data: T,
10}
11
12impl<T> RequestExtractor for QueryExtractor<T>
13where
14    T: serde::de::DeserializeOwned + Send + 'static,
15{
16    type Error = HttpError;
17
18    fn extract(request: &ElifRequest) -> Result<Self, Self::Error> {
19        let data = request.query()
20            .map_err(|e| HttpError::bad_request(format!("Invalid query parameters: {}", e)))?;
21        Ok(QueryExtractor { data })
22    }
23}
24
25impl<T> std::ops::Deref for QueryExtractor<T> {
26    type Target = T;
27
28    fn deref(&self) -> &Self::Target {
29        &self.data
30    }
31}
32
33/// Extract path parameters from the request
34pub struct PathExtractor<T> {
35    data: T,
36}
37
38impl<T> RequestExtractor for PathExtractor<T>
39where
40    T: serde::de::DeserializeOwned + Send + 'static,
41{
42    type Error = HttpError;
43
44    fn extract(request: &ElifRequest) -> Result<Self, Self::Error> {
45        let data = request.path_params()?;
46        Ok(PathExtractor { data })
47    }
48}
49
50impl<T> std::ops::Deref for PathExtractor<T> {
51    type Target = T;
52
53    fn deref(&self) -> &Self::Target {
54        &self.data
55    }
56}
57
58/// Extract JSON body from the request
59pub struct JsonExtractor<T> {
60    data: T,
61}
62
63impl<T> RequestExtractor for JsonExtractor<T>
64where
65    T: serde::de::DeserializeOwned + Send + 'static,
66{
67    type Error = HttpError;
68
69    fn extract(request: &ElifRequest) -> Result<Self, Self::Error> {
70        let data = request.json()
71            .map_err(|e| HttpError::bad_request(format!("Invalid JSON body: {}", e)))?;
72        Ok(JsonExtractor { data })
73    }
74}
75
76impl<T> std::ops::Deref for JsonExtractor<T> {
77    type Target = T;
78
79    fn deref(&self) -> &Self::Target {
80        &self.data
81    }
82}