ferrik-core 0.0.3

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
Documentation
//! Dual-format request input extractor (`ActionInput<T>`) and form helpers.
//!
//! Allows a single controller action to accept both `application/json` and
//! `application/x-www-form-urlencoded` (HTML form) payloads into the same `InputDTO`.

use axum::extract::{Form, FromRequest, Json, Request};
use axum::http::header;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer};
use validator::ValidationErrors;

use crate::error::{AppError, FormattedError};
use crate::response::Format;

/// Extracts a typed payload `T` from either JSON (`application/json`) or
/// URL-encoded HTML form data (`application/x-www-form-urlencoded`).
#[derive(Debug, Clone)]
pub struct ActionInput<T>(pub T);

impl<S, T> FromRequest<S> for ActionInput<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Send,
{
    type Rejection = FormattedError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let format = Format::negotiate(req.uri().path(), req.headers());
        let content_type = req
            .headers()
            .get(header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_ascii_lowercase();

        if content_type.contains("application/json") {
            match Json::<T>::from_request(req, state).await {
                Ok(Json(value)) => Ok(ActionInput(value)),
                Err(err) => Err(AppError::BadRequest(err.body_text()).with_format(format)),
            }
        } else {
            match Form::<T>::from_request(req, state).await {
                Ok(Form(value)) => Ok(ActionInput(value)),
                Err(err) => Err(AppError::BadRequest(err.body_text()).with_format(format)),
            }
        }
    }
}

/// Converts `validator::ValidationErrors` into a flat list of human-readable error strings.
pub fn validation_errors_to_vec(errors: &ValidationErrors) -> Vec<String> {
    let mut out = Vec::new();
    for (field, field_errors) in errors.field_errors() {
        for err in field_errors {
            let msg = err
                .message
                .as_ref()
                .map(|m| m.to_string())
                .unwrap_or_else(|| format!("{} failed validation ({})", field, err.code));
            out.push(format!("{}: {}", field, msg));
        }
    }
    if out.is_empty() {
        out.push("Validation failed".to_string());
    }
    out
}

/// Serde deserializer that accepts booleans from JSON (`true`/`false`) as well as
/// HTML checkbox form values (`"on"`, `"true"`, `"1"`, `"false"`, `"0"`, `""`).
pub fn deserialize_bool_from_anything<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum BoolOrString {
        Bool(bool),
        Int(i64),
        Str(String),
    }

    match BoolOrString::deserialize(deserializer)? {
        BoolOrString::Bool(b) => Ok(b),
        BoolOrString::Int(i) => Ok(i != 0),
        BoolOrString::Str(s) => match s.trim().to_ascii_lowercase().as_str() {
            "true" | "1" | "on" | "yes" => Ok(true),
            "false" | "0" | "off" | "no" | "" => Ok(false),
            other => Err(serde::de::Error::custom(format!(
                "invalid boolean value: {}",
                other
            ))),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::TestApp;
    use axum::http::StatusCode;
    use axum::routing::post;
    use axum::{Json, Router};
    use serde::Serialize;
    use validator::Validate;

    #[derive(Debug, Deserialize, Serialize, Validate)]
    struct PostInput {
        #[validate(length(min = 1, message = "cannot be blank"))]
        title: String,
        #[serde(default, deserialize_with = "deserialize_bool_from_anything")]
        published: bool,
    }

    async fn echo_input(ActionInput(input): ActionInput<PostInput>) -> Json<PostInput> {
        Json(input)
    }

    #[tokio::test]
    async fn extracts_json_and_form_into_same_dto() {
        let app = TestApp::spawn_with(|_db| async {
            Router::new().route("/posts", post(echo_input))
        })
        .await;

        let json_res: PostInput = app
            .post_json(
                "/posts",
                &serde_json::json!({ "title": "Hello", "published": true }),
            )
            .await
            .assert_ok()
            .json();
        assert_eq!(json_res.title, "Hello");
        assert!(json_res.published);

        let form_res: PostInput = app
            .post_form("/posts", &[("title", "From Form"), ("published", "on")])
            .await
            .assert_ok()
            .json();
        assert_eq!(form_res.title, "From Form");
        assert!(form_res.published);

        let unchecked_res: PostInput = app
            .post_form("/posts", &[("title", "Unchecked")])
            .await
            .assert_ok()
            .json();
        assert!(!unchecked_res.published);

        app.post_form("/posts", &[("published", "maybe")])
            .await
            .assert_status(StatusCode::BAD_REQUEST);
    }

    #[test]
    fn converts_validation_errors_to_strings() {
        let bad = PostInput {
            title: "".into(),
            published: false,
        };
        let errs = bad.validate().unwrap_err();
        let list = validation_errors_to_vec(&errs);
        assert_eq!(list, vec!["title: cannot be blank"]);
    }
}