Custom extractor to validate query string. #2081
-
I custom extractor by implementing FromRequest to validate query struct and i get the error that "the trait FromRequest<(), Body, _> is not implemented for Validated". Here my implementation, some one help me please .
|
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Jul 10, 2023
Replies: 1 comment 1 reply
-
The issue is actually with the This works for me use axum::{
async_trait,
extract::{FromRequest, FromRequestParts, Query},
http, response,
};
use serde::{Deserialize, Serialize};
use validator::Validate;
pub struct Validated<T>(pub T);
#[async_trait]
impl<S, B, T> FromRequest<S, B> for Validated<T>
where
S: Send + Sync,
B: Send + 'static,
T: Validate,
Query<T>: FromRequestParts<S>,
{
type Rejection = (http::StatusCode, String);
async fn from_request(req: http::Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let query = Query::<T>::from_request(req, state).await;
if let Ok(Query(data)) = query {
match data.validate() {
Ok(_) => Ok(Validated(data)),
Err(err) => Err((http::StatusCode::BAD_REQUEST, err.to_string())),
}
} else {
Err((
http::StatusCode::INTERNAL_SERVER_ERROR,
"internal server error".to_string(),
))
}
}
}
// my handler
#[derive(Deserialize, Serialize, Validate)]
pub struct Pagination {
#[validate(range(min = 1))]
page: usize,
#[validate(range(max = 100))]
per_page: usize,
}
#[axum::debug_handler]
pub async fn get_query_string(
Validated(pagination): Validated<Pagination>,
) -> response::Json<Pagination> {
response::Json(pagination)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
goni098
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The issue is actually with the
Query<T>: FromRequest<S, B>
bound. You'll wanna useQuery<T>: FromRequestParts<S>
instead sinceQuery
doesn't need the request body.This works for me