Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

return validation json response #1174

Merged
merged 4 commits into from
Jan 13, 2025
Merged

return validation json response #1174

merged 4 commits into from
Jan 13, 2025

Conversation

kaplanelad
Copy link
Contributor

@kaplanelad kaplanelad commented Jan 12, 2025

Previously, the controller did not support automatic validation of POST parameters. Validation was done manually after deserialization using the serde_json library. For instance, the developer would create a struct, add validation rules using the Validate trait, and manually handle the validation errors in the controller.

#[derive(Debug, Deserialize, Validate)]
pub struct DataParams {
    #[validate(length(min = 5, message = "message_str"))]
    pub name: String,
    #[validate(email)]
    pub email: String,
}

#[debug_handler]
pub async fn index(
    State(_ctx): State<AppContext>,
    Json(params): Json<DataParams>,
) -> Result<Response> {
    // Manual validation
    let validate_res = params.validate();
    if let Err(errors) = validate_res {
        // Handle errors manually
        return Err(errors.into());
    }

    // Continue processing if validation succeeds
    format::empty()
}

New Implementation:
The updated implementation introduces a JsonValidate and FormValidate and with messages response: JsonValidateWithMessage and FormValidateWithMessage extractors, which automatically handles validation and returns a JSON response for validation errors. This eliminates the need for manual validation logic in the controller.

#[derive(Debug, Deserialize, Validate)]
pub struct DataParams {
    #[validate(length(min = 5, message = "message_str"))]
    pub name: String,
    #[validate(email)]
    pub email: String,
}

#[debug_handler]
pub async fn index(
    State(_ctx): State<AppContext>,
    JsonValidate(params): JsonValidate<DataParams>,
) -> Result<Response> {
    // Validation is automatically handled by JsonValidate
    format::empty()
}

If validation fails, JsonValidate automatically returns a structured JSON response like the following:

{
  "errors": {
    "email": [
      {
        "code": "email",
        "message": null,
        "params": { "value": "invalid" }
      }
    ],
    "name": [
      {
        "code": "length",
        "message": "message_str",
        "params": { "min": 5, "value": "test" }
      }
    ]
  }
}

@kaplanelad kaplanelad changed the title allow return validation json response return validation json response Jan 12, 2025
@kaplanelad kaplanelad merged commit b4ca273 into master Jan 13, 2025
9 checks passed
@kaplanelad kaplanelad mentioned this pull request Jan 20, 2025
@turboladen
Copy link

I'm a bit confused here and was wondering if I might get a hand? After trying to implement this pattern for my own type and route, I copied the example code and brought it into my project, and it doesn't compile:

 3  error[E0277]: the trait bound `loco_rs::prelude::JsonValidate<DataParams>: FromRequest<loco_rs::prelude::AppContext, _>` is not satisfied                                                                          ▐
   --> crates/ding/src/controllers/chat.rs:72:27                                                                                                                                                                       ▐
    |                                                                                                                                                                                                                  ▐
 72 |     JsonValidate(params): JsonValidate<DataParams>,                                                                                                                                                              ▐
    |                           ^^^^^^^^^^^^ the trait `FromRequest<loco_rs::prelude::AppContext, _>` is not implemented for `loco_rs::prelude::JsonValidate<DataParams>`                                              ▐
    |                                                                                                                                                                                                                  ▐
    = note: Function argument is not a valid axum extractor.                                                                                                                                                           ▐
            See `https://docs.rs/axum/0.8/axum/extract/index.html` for details                                                                                                                                         ▐
    = help: the trait `FromRequest<S>` is implemented for `loco_rs::prelude::JsonValidate<T>`                                                                                                                          ▐
 note: required by a bound in `chat::__axum_macros_check_index_1_from_request_check`                                                                                                                                   ▐
   --> crates/ding/src/controllers/chat.rs:72:27                                                                                                                                                                       ▐
    |                                                                                                                                                                                                                  ▐
 72 |     JsonValidate(params): JsonValidate<DataParams>,                                                                                                                                                              ▐
    |                           ^^^^^^^^^^^^ required by this bound in `__axum_macros_check_index_1_from_request_check`  

Any thoughts on what I might be missing?

@turboladen
Copy link

Any thoughts on what I might be missing?

I figured it out: I was running validator 0.20.0, but looks like loco-rs wants 0.19.0. Once I downgraded to that, I was in business.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants