-
Notifications
You must be signed in to change notification settings - Fork 284
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
return validation json response (#1174)
* allow return validation json response * allow return validation json response * docs
- Loading branch information
1 parent
a602367
commit b4ca273
Showing
9 changed files
with
266 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
pub mod validate; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
use crate::Error; | ||
use axum::extract::{Form, FromRequest, Json, Request}; | ||
use serde::de::DeserializeOwned; | ||
use validator::Validate; | ||
|
||
#[derive(Debug, Clone, Copy, Default)] | ||
pub struct JsonValidateWithMessage<T>(pub T); | ||
|
||
impl<T, S> FromRequest<S> for JsonValidateWithMessage<T> | ||
where | ||
T: DeserializeOwned + Validate, | ||
S: Send + Sync, | ||
{ | ||
type Rejection = Error; | ||
|
||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { | ||
let Json(value) = Json::<T>::from_request(req, state).await?; | ||
value.validate()?; | ||
Ok(Self(value)) | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, Default)] | ||
pub struct FormValidateWithMessage<T>(pub T); | ||
|
||
impl<T, S> FromRequest<S> for FormValidateWithMessage<T> | ||
where | ||
T: DeserializeOwned + Validate, | ||
S: Send + Sync, | ||
{ | ||
type Rejection = Error; | ||
|
||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { | ||
let Form(value) = Form::<T>::from_request(req, state).await?; | ||
value.validate()?; | ||
Ok(Self(value)) | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, Default)] | ||
pub struct JsonValidate<T>(pub T); | ||
|
||
impl<T, S> FromRequest<S> for JsonValidate<T> | ||
where | ||
T: DeserializeOwned + Validate, | ||
S: Send + Sync, | ||
{ | ||
type Rejection = Error; | ||
|
||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { | ||
let Json(value) = Json::<T>::from_request(req, state).await?; | ||
value.validate().map_err(|err| { | ||
tracing::debug!(err = ?err, "request validation error occurred"); | ||
Error::BadRequest(String::new()) | ||
})?; | ||
Ok(Self(value)) | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, Default)] | ||
pub struct FormValidate<T>(pub T); | ||
|
||
impl<T, S> FromRequest<S> for FormValidate<T> | ||
where | ||
T: DeserializeOwned + Validate, | ||
S: Send + Sync, | ||
{ | ||
type Rejection = Error; | ||
|
||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { | ||
let Form(value) = Form::<T>::from_request(req, state).await?; | ||
value.validate().map_err(|err| { | ||
tracing::debug!(err = ?err, "request validation error occurred"); | ||
Error::BadRequest(String::new()) | ||
})?; | ||
Ok(Self(value)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
mod into_response; | ||
mod middlewares; | ||
mod validation_extractor; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
use crate::infra_cfg; | ||
use loco_rs::{prelude::*, tests_cfg}; | ||
use serde::{Deserialize, Serialize}; | ||
use serial_test::serial; | ||
use validator::Validate; | ||
|
||
#[derive(Debug, Deserialize, Serialize, Validate)] | ||
pub struct Data { | ||
#[validate(length(min = 5, message = "message_str"))] | ||
pub name: String, | ||
#[validate(email)] | ||
pub email: String, | ||
} | ||
|
||
async fn validation_with_response( | ||
JsonValidateWithMessage(_params): JsonValidateWithMessage<Data>, | ||
) -> Result<Response> { | ||
format::json(()) | ||
} | ||
|
||
async fn simple_validation(JsonValidate(_params): JsonValidate<Data>) -> Result<Response> { | ||
format::json(()) | ||
} | ||
|
||
#[tokio::test] | ||
#[serial] | ||
async fn can_validation_with_response() { | ||
let ctx = tests_cfg::app::get_app_context().await; | ||
|
||
let handle = | ||
infra_cfg::server::start_with_route(ctx, "/", post(validation_with_response)).await; | ||
|
||
let client = reqwest::Client::new(); | ||
let res = client | ||
.post(infra_cfg::server::get_base_url()) | ||
.json(&serde_json::json!({"name": "test", "email": "invalid"})) | ||
.send() | ||
.await | ||
.expect("Valid response"); | ||
|
||
assert_eq!(res.status(), 400); | ||
|
||
let res_text = res.text().await.expect("response text"); | ||
let res_json: serde_json::Value = serde_json::from_str(&res_text).expect("Valid JSON response"); | ||
|
||
let expected_json = serde_json::json!( | ||
{ | ||
"errors":{ | ||
"email":[{"code":"email","message":null,"params":{"value":"invalid"}}], | ||
"name":[{"code":"length","message":"message_str","params":{"min":5,"value":"test"}}] | ||
} | ||
}); | ||
|
||
assert_eq!(res_json, expected_json); | ||
|
||
handle.abort(); | ||
} | ||
|
||
#[tokio::test] | ||
#[serial] | ||
async fn can_validation_without_response() { | ||
let ctx = tests_cfg::app::get_app_context().await; | ||
|
||
let handle = infra_cfg::server::start_with_route(ctx, "/", post(simple_validation)).await; | ||
|
||
let client = reqwest::Client::new(); | ||
let res = client | ||
.post(infra_cfg::server::get_base_url()) | ||
.json(&serde_json::json!({"name": "test", "email": "invalid"})) | ||
.send() | ||
.await | ||
.expect("Valid response"); | ||
|
||
assert_eq!(res.status(), 400); | ||
|
||
let res_text = res.text().await.expect("response text"); | ||
let res_json: serde_json::Value = serde_json::from_str(&res_text).expect("Valid JSON response"); | ||
|
||
let expected_json = serde_json::json!( | ||
{ | ||
"error": "Bad Request" | ||
} | ||
); | ||
|
||
assert_eq!(res_json, expected_json); | ||
|
||
handle.abort(); | ||
} |