use axum::{
Json,
extract::{FromRequest, Request},
http::{StatusCode, header::CONTENT_TYPE},
response::{IntoResponse, Response},
};
use serde::de::DeserializeOwned;
use std::collections::BTreeMap;
use validator::{Validate, ValidationErrors};
pub struct Form<T>(pub T);
pub fn errors_map(e: &ValidationErrors) -> BTreeMap<String, String> {
e.field_errors()
.into_iter()
.filter_map(|(f, v)| {
let e = v.first()?;
Some((
f.to_string(),
e.message.as_deref().unwrap_or(&e.code).to_string(),
))
})
.collect()
}
fn bad_request() -> Response {
StatusCode::BAD_REQUEST.into_response()
}
impl<S, T> FromRequest<S> for Form<T>
where
S: Send + Sync,
T: DeserializeOwned + Validate + Send,
{
type Rejection = Response;
async fn from_request(req: Request, state: &S) -> Result<Self, Response> {
let h = req.headers();
#[cfg(feature = "inertia")]
let wants_json = h.get("x-inertia").is_none()
&& h.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("json"));
let is_json = h
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
#[cfg(feature = "inertia")]
let headers = h.clone();
#[cfg(feature = "inertia")]
let session = req.extensions().get::<tower_sessions::Session>().cloned();
let value: T = if is_json {
Json::<T>::from_request(req, state)
.await
.map_err(|_| bad_request())?
.0
} else {
axum::Form::<T>::from_request(req, state)
.await
.map_err(|_| bad_request())?
.0
};
let Err(errs) = value.validate() else {
return Ok(Form(value));
};
#[cfg(feature = "inertia")]
if let Some(s) = session.filter(|_| !wants_json) {
crate::inertia::flash_errors(&s, errors_map(&errs)).await;
return Err(crate::inertia::redirect_back(&headers));
}
let errors: BTreeMap<String, Vec<String>> = errs
.field_errors()
.into_iter()
.map(|(f, v)| {
let m = v
.iter()
.map(|e| e.message.as_deref().unwrap_or(&e.code).to_string());
(f.to_string(), m.collect())
})
.collect();
Err((
StatusCode::UNPROCESSABLE_ENTITY,
Json(serde_json::json!({ "errors": errors })),
)
.into_response())
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, http::header::ACCEPT};
use serde::Deserialize;
#[derive(Deserialize, Validate)]
struct In {
#[validate(length(min = 3, message = "too short"))]
name: String,
}
#[allow(clippy::result_large_err)]
async fn call(ct: &str, accept: &str, body: &str) -> Result<Form<In>, Response> {
let r = Request::post("/")
.header(CONTENT_TYPE, ct)
.header(ACCEPT, accept)
.header("referer", "http://x/back")
.body(Body::from(body.to_string()))
.unwrap();
Form::<In>::from_request(r, &()).await
}
#[tokio::test]
async fn modes() {
let r = call("application/json", "application/json", r#"{"name":"ab"}"#)
.await
.err()
.unwrap();
assert_eq!(r.status(), 422);
let b = axum::body::to_bytes(r.into_body(), 1024).await.unwrap();
assert_eq!(&b[..], br#"{"errors":{"name":["too short"]}}"#);
let r = call("application/x-www-form-urlencoded", "text/html", "name=ab")
.await
.err()
.unwrap();
assert_eq!(r.status(), 422);
let r = call("application/json", "*/*", "{nope")
.await
.err()
.unwrap();
assert_eq!(r.status(), 400);
let ok = call("application/x-www-form-urlencoded", "*/*", "name=abcd")
.await
.ok()
.unwrap();
assert_eq!(ok.0.name, "abcd");
}
}