-
Notifications
You must be signed in to change notification settings - Fork 1
/
with_validation.rs
66 lines (57 loc) · 1.93 KB
/
with_validation.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::marker::PhantomData;
use super::Unwrapable;
use super::WithValidationRejection;
use axum::async_trait;
use axum::extract::FromRequest;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::Request;
use garde::Unvalidated;
use garde::Valid;
use garde::Validate;
#[derive(Debug)]
pub struct WithValidation<T, E>(pub Valid<T>, pub PhantomData<E>);
impl<T, E> From<Valid<T>> for WithValidation<T, E> {
fn from(value: Valid<T>) -> Self {
WithValidation(value, Default::default())
}
}
#[async_trait]
impl<S, T, E> FromRequestParts<S> for WithValidation<T, E>
where
S: Send + Sync,
E: FromRequestParts<S> + Unwrapable<T>,
T: Validate<Context = ()>,
{
type Rejection = WithValidationRejection<E::Rejection>;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let extracted = E::from_request_parts(parts, state)
.await
.map_err(WithValidationRejection::ExtractionError)?;
let t: T = extracted.extract();
let valid = Unvalidated::from(t)
.validate(&())
.map_err(WithValidationRejection::ValidationError)?;
Ok(WithValidation(valid, Default::default()))
}
}
#[async_trait]
impl<S, B, T, E> FromRequest<S, B> for WithValidation<T, E>
where
B: Send + 'static,
S: Send + Sync,
E: FromRequest<S, B> + Unwrapable<T>,
T: Validate<Context = ()>,
{
type Rejection = WithValidationRejection<E::Rejection>;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let extracted = E::from_request(req, state)
.await
.map_err(WithValidationRejection::ExtractionError)?;
let t: T = extracted.extract();
let valid = Unvalidated::from(t)
.validate(&())
.map_err(WithValidationRejection::ValidationError)?;
Ok(WithValidation(valid, Default::default()))
}
}