-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Nicer path extractor, uses query params
- Loading branch information
1 parent
634e10b
commit ed18002
Showing
5 changed files
with
148 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,142 @@ | ||
use super::FromRequestParts; | ||
use crate::SharedAppState; | ||
use http::request::Parts; | ||
use std::convert::Infallible; | ||
use crate::{response::IntoResponse, SharedAppState}; | ||
use http::Response; | ||
use http::{request::Parts, StatusCode}; | ||
use std::collections::HashMap; | ||
use std::str::FromStr; | ||
use std::sync::Arc; | ||
|
||
pub struct Path(pub String); | ||
pub struct Path<T>(pub T); | ||
|
||
impl FromRequestParts for Path { | ||
type Rejection = Infallible; | ||
#[derive(Debug)] | ||
pub enum PathRejection { | ||
MissingPathParams, | ||
ParseError(String), | ||
WrongNumberOfParameters { expected: usize, actual: usize }, | ||
} | ||
|
||
impl IntoResponse for PathRejection { | ||
fn into_response(self) -> crate::response::AppResponse { | ||
let (status, body) = match self { | ||
Self::MissingPathParams => ( | ||
StatusCode::INTERNAL_SERVER_ERROR, | ||
"Missing path parameters".into(), | ||
), | ||
Self::ParseError(err) => ( | ||
StatusCode::BAD_REQUEST, | ||
format!("Failed to parse path parameter: {err}"), | ||
), | ||
Self::WrongNumberOfParameters { expected, actual } => ( | ||
StatusCode::BAD_REQUEST, | ||
format!("Wrong number of path parameters. Expected {expected}, got {actual}"), | ||
), | ||
}; | ||
|
||
Response::builder() | ||
.status(status) | ||
.body(body.into()) | ||
.unwrap() | ||
} | ||
} | ||
|
||
pub trait FromPath: Sized { | ||
fn from_path(map: &HashMap<String, String>) -> Result<Self, PathRejection>; | ||
} | ||
|
||
impl<T> FromRequestParts for Path<T> | ||
where | ||
T: FromPath, | ||
{ | ||
type Rejection = PathRejection; | ||
|
||
fn from_request_parts( | ||
parts: &mut Parts, | ||
_state: &SharedAppState, | ||
) -> Result<Self, Self::Rejection> { | ||
let params = parts | ||
.extensions | ||
.get::<Arc<HashMap<String, String>>>() | ||
.ok_or(PathRejection::MissingPathParams)?; | ||
|
||
fn from_request_parts(parts: &mut Parts, _: &SharedAppState) -> Result<Self, Self::Rejection> { | ||
Ok(Self(parts.uri.path().to_string())) | ||
T::from_path(params).map(Path) | ||
} | ||
} | ||
|
||
impl<T> FromPath for T | ||
where | ||
T: FromStr, | ||
T::Err: std::fmt::Display, | ||
{ | ||
fn from_path(map: &HashMap<String, String>) -> Result<Self, PathRejection> { | ||
if map.len() != 1 { | ||
return Err(PathRejection::WrongNumberOfParameters { | ||
expected: 1, | ||
actual: map.len(), | ||
}); | ||
} | ||
|
||
let (_, value) = map.iter().next().unwrap(); | ||
T::from_str(value).map_err(|e| PathRejection::ParseError(e.to_string())) | ||
} | ||
} | ||
|
||
pub trait FromPathTuple: Sized { | ||
fn from_path_tuple(map: &HashMap<String, String>) -> Result<Self, PathRejection>; | ||
} | ||
|
||
macro_rules! count_idents { | ||
() => (0); | ||
($T:ident $(,$Rest:ident)*) => (1 + count_idents!($($Rest),*)); | ||
} | ||
|
||
macro_rules! impl_from_path_tuple { | ||
($($T:ident),+) => { | ||
impl<$($T),+> FromPathTuple for ($($T,)+) | ||
where | ||
$($T: FromStr,)+ | ||
$($T::Err: std::fmt::Display,)+ | ||
{ | ||
fn from_path_tuple(map: &HashMap<String, String>) -> Result<Self, PathRejection> { | ||
let expected = count_idents!($($T),+); | ||
if map.len() != expected { | ||
return Err(PathRejection::WrongNumberOfParameters { | ||
expected, | ||
actual: map.len(), | ||
}); | ||
} | ||
|
||
let mut values = map.values(); | ||
Ok(( | ||
$( | ||
values.next() | ||
.ok_or(PathRejection::MissingPathParams)? | ||
.parse::<$T>() | ||
.map_err(|e| PathRejection::ParseError(e.to_string()))?, | ||
)+ | ||
)) | ||
} | ||
} | ||
}; | ||
} | ||
|
||
macro_rules! all_the_tuples { | ||
($name:ident) => { | ||
$name!(T1, T2); | ||
$name!(T1, T2, T3); | ||
$name!(T1, T2, T3, T4); | ||
$name!(T1, T2, T3, T4, T5); | ||
$name!(T1, T2, T3, T4, T5, T6); | ||
$name!(T1, T2, T3, T4, T5, T6, T7); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); | ||
$name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); | ||
}; | ||
} | ||
|
||
all_the_tuples!(impl_from_path_tuple); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters