mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-23 00:00:15 +02:00
new(axum-extra): Added WithRejection base impl
Based on @jplatte's version (https://github.com/tokio-rs/axum/issues/1116#issuecomment-1215048273), with slight changes - Using `From<E::Rejection>` to define the trait bound on a more concise way - Renamed variables to something more meaningfull
This commit is contained in:
@@ -32,6 +32,7 @@ protobuf = ["dep:prost"]
|
||||
query = ["dep:serde", "dep:serde_html_form"]
|
||||
spa = ["tower-http/fs"]
|
||||
typed-routing = ["dep:axum-macros", "dep:serde", "dep:percent-encoding"]
|
||||
with_rejection = []
|
||||
|
||||
[dependencies]
|
||||
axum = { path = "../axum", version = "0.5", default-features = false }
|
||||
|
||||
@@ -11,6 +11,9 @@ pub mod cookie;
|
||||
#[cfg(feature = "query")]
|
||||
mod query;
|
||||
|
||||
#[cfg(feature = "with_rejection")]
|
||||
mod with_rejection;
|
||||
|
||||
pub use self::cached::Cached;
|
||||
|
||||
#[cfg(feature = "cookie")]
|
||||
@@ -31,3 +34,6 @@ pub use self::query::Query;
|
||||
#[cfg(feature = "json-lines")]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::json_lines::JsonLines;
|
||||
|
||||
#[cfg(feature = "with_rejection")]
|
||||
pub use self::with_rejection::WithRejection;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use axum::async_trait;
|
||||
use axum::extract::{FromRequest, RequestParts};
|
||||
use axum::response::IntoResponse;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct WithRejection<E, R>(pub E, pub PhantomData<R>);
|
||||
|
||||
impl<E, R> WithRejection<E, R> {
|
||||
fn into_inner(self) -> E {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R> Deref for WithRejection<E, R> {
|
||||
type Target = E;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, R> DerefMut for WithRejection<E, R> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B, E, R> FromRequest<B> for WithRejection<E, R>
|
||||
where
|
||||
B: Send,
|
||||
E: FromRequest<B>,
|
||||
R: From<E::Rejection> + IntoResponse,
|
||||
{
|
||||
type Rejection = R;
|
||||
|
||||
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
|
||||
match req.extract::<E>().await {
|
||||
Ok(extractor) => Ok(WithRejection(extractor, PhantomData)),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user