Skip to content

Commit

Permalink
Implement OptionalFromRequestParts for Path<T>
Browse files Browse the repository at this point in the history
… and deprecate OptionalPath.
  • Loading branch information
jplatte committed Nov 26, 2024
1 parent e382cce commit 42bcd63
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 14 deletions.
6 changes: 3 additions & 3 deletions axum-extra/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ pub mod multipart;
#[cfg(feature = "scheme")]
mod scheme;

pub use self::{
cached::Cached, host::Host, optional_path::OptionalPath, with_rejection::WithRejection,
};
#[allow(deprecated)]
pub use self::optional_path::OptionalPath;
pub use self::{cached::Cached, host::Host, with_rejection::WithRejection};

#[cfg(feature = "cookie")]
pub use self::cookie::CookieJar;
Expand Down
18 changes: 8 additions & 10 deletions axum-extra/src/extract/optional_path.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::{
extract::{path::ErrorKind, rejection::PathRejection, FromRequestParts, Path},
extract::{rejection::PathRejection, FromRequestParts, Path},
RequestPartsExt,
};
use serde::de::DeserializeOwned;
Expand Down Expand Up @@ -31,9 +31,11 @@ use serde::de::DeserializeOwned;
/// .route("/blog/{page}", get(render_blog));
/// # let app: Router = app;
/// ```
#[deprecated = "Use Option<Path<_>> instead"]
#[derive(Debug)]
pub struct OptionalPath<T>(pub Option<T>);

#[allow(deprecated)]
impl<T, S> FromRequestParts<S> for OptionalPath<T>
where
T: DeserializeOwned + Send + 'static,
Expand All @@ -45,19 +47,15 @@ where
parts: &mut http::request::Parts,
_: &S,
) -> Result<Self, Self::Rejection> {
match parts.extract::<Path<T>>().await {
Ok(Path(params)) => Ok(Self(Some(params))),
Err(PathRejection::FailedToDeserializePathParams(e))
if matches!(e.kind(), ErrorKind::WrongNumberOfParameters { got: 0, .. }) =>
{
Ok(Self(None))
}
Err(e) => Err(e),
}
parts
.extract::<Option<Path<T>>>()
.await
.map(|opt| Self(opt.map(|Path(x)| x)))
}
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
use std::num::NonZeroU32;

Expand Down
29 changes: 28 additions & 1 deletion axum/src/extract/path/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ use crate::{
routing::url_params::UrlParams,
util::PercentDecodedStr,
};
use axum_core::response::{IntoResponse, Response};
use axum_core::{
extract::OptionalFromRequestParts,
response::{IntoResponse, Response},
RequestPartsExt as _,
};
use http::{request::Parts, StatusCode};
use serde::de::DeserializeOwned;
use std::{fmt, sync::Arc};
Expand Down Expand Up @@ -176,6 +180,29 @@ where
}
}

impl<T, S> OptionalFromRequestParts<S> for Path<T>
where
T: DeserializeOwned + Send + 'static,
S: Send + Sync,
{
type Rejection = PathRejection;

async fn from_request_parts(
parts: &mut Parts,
_state: &S,
) -> Result<Option<Self>, Self::Rejection> {
match parts.extract::<Self>().await {
Ok(Self(params)) => Ok(Some(Self(params))),
Err(PathRejection::FailedToDeserializePathParams(e))
if matches!(e.kind(), ErrorKind::WrongNumberOfParameters { got: 0, .. }) =>
{
Ok(None)
}
Err(e) => Err(e),
}
}
}

// this wrapper type is used as the deserializer error to hide the `serde::de::Error` impl which
// would otherwise be public if we used `ErrorKind` as the error directly
#[derive(Debug)]
Expand Down

0 comments on commit 42bcd63

Please sign in to comment.