Skip to content

Commit

Permalink
Also implement OptionalFromRequestParts for Query in axum
Browse files Browse the repository at this point in the history
  • Loading branch information
jplatte committed Dec 30, 2023
1 parent 8b1a607 commit d988573
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion axum/src/extract/query.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{rejection::*, FromRequestParts};
use super::{rejection::*, FromRequestParts, OptionalFromRequestParts};
use async_trait::async_trait;
use http::{request::Parts, Uri};
use serde::de::DeserializeOwned;
Expand Down Expand Up @@ -59,6 +59,28 @@ where
}
}

#[async_trait]
impl<T, S> OptionalFromRequestParts<S> for Query<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = QueryRejection;

async fn from_request_parts(
parts: &mut Parts,
_state: &S,
) -> Result<Option<Self>, Self::Rejection> {
if let Some(query) = parts.uri.query() {
let value = serde_urlencoded::from_str(query)
.map_err(FailedToDeserializeQueryString::from_err)?;
Ok(Some(Self(value)))
} else {
Ok(None)
}
}
}

impl<T> Query<T>
where
T: DeserializeOwned,
Expand Down

0 comments on commit d988573

Please sign in to comment.