2022-08-19 15:11:03 +02:00
|
|
|
//! Manual implementation of `FromRequest` that wraps another extractor
|
|
|
|
|
//!
|
|
|
|
|
//! + Powerful API: Implementing `FromRequest` grants access to `RequestParts`
|
|
|
|
|
//! and `async/await`. This means that you can create more powerful rejections
|
|
|
|
|
//! - Boilerplate: Requires creating a new extractor for every custom rejection
|
|
|
|
|
//! - Complexity: Manually implementing `FromRequest` results on more complex code
|
|
|
|
|
use axum::{
|
2023-03-20 21:02:40 +01:00
|
|
|
extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request},
|
2022-08-19 15:11:03 +02:00
|
|
|
http::StatusCode,
|
|
|
|
|
response::IntoResponse,
|
2022-10-04 19:26:51 +02:00
|
|
|
RequestPartsExt,
|
2022-08-19 15:11:03 +02:00
|
|
|
};
|
|
|
|
|
use serde_json::{json, Value};
|
|
|
|
|
|
|
|
|
|
pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse {
|
|
|
|
|
Json(dbg!(value));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// We define our own `Json` extractor that customizes the error from `axum::Json`
|
2022-08-19 22:38:46 +02:00
|
|
|
pub struct Json<T>(pub T);
|
2022-08-19 15:11:03 +02:00
|
|
|
|
2023-03-12 16:37:32 +01:00
|
|
|
impl<S, T> FromRequest<S> for Json<T>
|
2022-08-19 15:11:03 +02:00
|
|
|
where
|
2023-03-12 16:37:32 +01:00
|
|
|
axum::Json<T>: FromRequest<S, Rejection = JsonRejection>,
|
2022-08-19 15:11:03 +02:00
|
|
|
S: Send + Sync,
|
|
|
|
|
{
|
|
|
|
|
type Rejection = (StatusCode, axum::Json<Value>);
|
|
|
|
|
|
2023-03-20 21:02:40 +01:00
|
|
|
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
2022-08-22 12:23:20 +02:00
|
|
|
let (mut parts, body) = req.into_parts();
|
|
|
|
|
|
2022-10-04 19:26:51 +02:00
|
|
|
// We can use other extractors to provide better rejection messages.
|
|
|
|
|
// For example, here we are using `axum::extract::MatchedPath` to
|
|
|
|
|
// provide a better error message.
|
2022-08-22 12:23:20 +02:00
|
|
|
//
|
2022-10-04 19:26:51 +02:00
|
|
|
// Have to run that first since `Json` extraction consumes the request.
|
|
|
|
|
let path = parts
|
|
|
|
|
.extract::<MatchedPath>()
|
2022-08-22 12:23:20 +02:00
|
|
|
.await
|
|
|
|
|
.map(|path| path.as_str().to_owned())
|
|
|
|
|
.ok();
|
|
|
|
|
|
|
|
|
|
let req = Request::from_parts(parts, body);
|
|
|
|
|
|
|
|
|
|
match axum::Json::<T>::from_request(req, state).await {
|
2022-08-19 15:11:03 +02:00
|
|
|
Ok(value) => Ok(Self(value.0)),
|
|
|
|
|
// convert the error from `axum::Json` into whatever we want
|
|
|
|
|
Err(rejection) => {
|
|
|
|
|
let payload = json!({
|
2023-02-25 15:02:02 +01:00
|
|
|
"message": rejection.body_text(),
|
2022-08-19 15:11:03 +02:00
|
|
|
"origin": "custom_extractor",
|
|
|
|
|
"path": path,
|
|
|
|
|
});
|
|
|
|
|
|
2023-02-25 15:02:02 +01:00
|
|
|
Err((rejection.status(), axum::Json(payload)))
|
2022-08-19 15:11:03 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|