mmtickets_common/middlewares/
user_extractor.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
use crate::domain::UserPayload;
use axum::RequestExt;
use axum::{async_trait, body::HttpBody, extract::FromRequest, http::Request, BoxError, Json};

use validator::Validate;

use super::CommonError;

#[async_trait]
impl<S, B> FromRequest<S, B> for UserPayload
where
    B: HttpBody + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    type Rejection = CommonError;

    async fn from_request(request: Request<B>, _state: &S) -> Result<Self, Self::Rejection> {
        let Json(user) = request
            .extract::<Json<UserPayload>, _>()
            .await
            .map_err(|e| CommonError::new(axum::http::StatusCode::BAD_REQUEST, e.to_string()))?;

        if let Err(errors) = user.validate() {
            return Err(CommonError::new(
                axum::http::StatusCode::BAD_REQUEST,
                errors.to_string(),
            ));
        }
        Ok(user)
    }
}