use crate::common::{
VldHttpError, cookie_headers_to_json, headers_to_json, parse_form_body, parse_json_body,
path_params_to_json, percent_decode, query_string_to_json, require_form_content_type,
require_json_content_type,
};
use axum::extract::rejection::RawPathParamsRejection;
use axum::extract::{
FromRequest, FromRequestParts, MatchedPath, OriginalUri, RawPathParams, Request,
};
use axum::response::{IntoResponse, Response};
use http::request::Parts;
use http::{StatusCode, header};
use vld::schema::VldParse;
pub struct VldJsonRejection(VldHttpError);
impl VldJsonRejection {
pub fn error(&self) -> &vld::error::VldError {
self.0.error()
}
pub fn status(&self) -> StatusCode {
StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
}
pub fn body(&self) -> serde_json::Value {
self.0.body()
}
}
impl From<VldHttpError> for VldJsonRejection {
fn from(e: VldHttpError) -> Self {
Self(e)
}
}
impl From<vld::error::VldError> for VldJsonRejection {
fn from(e: vld::error::VldError) -> Self {
Self(e.into())
}
}
impl IntoResponse for VldJsonRejection {
fn into_response(self) -> Response {
(
self.status(),
[(http::header::CONTENT_TYPE, "application/json")],
self.0.body().to_string(),
)
.into_response()
}
}
impl std::fmt::Display for VldJsonRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Debug for VldJsonRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VldJsonRejection")
.field("error", self.error())
.field("status", &self.status())
.finish()
}
}
impl std::error::Error for VldJsonRejection {}
async fn read_body<S: Send + Sync>(req: Request, state: &S) -> Result<bytes::Bytes, VldHttpError> {
<bytes::Bytes as FromRequest<S>>::from_request(req, state)
.await
.map_err(|rejection| {
if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE {
VldHttpError::payload_too_large()
} else {
VldHttpError::parse(format!("Failed to read request body: {rejection}"))
}
})
}
fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, VldJsonRejection> {
crate::common::parse_coerced(value).map_err(VldJsonRejection::from)
}
fn content_type(headers: &http::HeaderMap) -> Option<&str> {
headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
}
fn lossy_path_params(parts: &Parts) -> serde_json::Value {
let Some(matched) = parts.extensions.get::<MatchedPath>() else {
return serde_json::json!({});
};
let uri = parts
.extensions
.get::<OriginalUri>()
.map_or(&parts.uri, |o| &o.0);
let mut values = uri.path().split('/');
let mut params = Vec::new();
for pattern in matched.as_str().split('/') {
let value = values.next();
let Some(name) = pattern.strip_prefix('{').and_then(|p| p.strip_suffix('}')) else {
continue;
};
if let Some(name) = name.strip_prefix('*') {
let rest: Vec<&str> = value.into_iter().chain(values.by_ref()).collect();
params.push((name, percent_decode(&rest.join("/"))));
break;
}
if let Some(value) = value {
params.push((name, percent_decode(value)));
}
}
path_params_to_json(params.iter().map(|(k, v)| (*k, v.as_str())))
}
pub struct VldJson<T>(pub T);
impl<S, T> FromRequest<S> for VldJson<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
require_json_content_type(content_type(req.headers()))?;
let body = read_body(req, state).await?;
T::vld_parse_value(&parse_json_body(&body)?)
.map(VldJson)
.map_err(VldJsonRejection::from)
}
}
pub struct VldQuery<T>(pub T);
impl<S, T> FromRequestParts<S> for VldQuery<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
validate(&query_string_to_json(parts.uri.query().unwrap_or(""))).map(VldQuery)
}
}
pub struct VldPath<T>(pub T);
impl<S, T> FromRequestParts<S> for VldPath<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let value = match RawPathParams::from_request_parts(parts, state).await {
Ok(params) => path_params_to_json(¶ms),
Err(RawPathParamsRejection::InvalidUtf8InPathParam(_)) => lossy_path_params(parts),
Err(_) => serde_json::json!({}),
};
validate(&value).map(VldPath)
}
}
pub struct VldForm<T>(pub T);
impl<S, T> FromRequest<S> for VldForm<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
require_form_content_type(content_type(req.headers()))?;
let body = read_body(req, state).await?;
validate(&parse_form_body(&body)?).map(VldForm)
}
}
pub struct VldHeaders<T>(pub T);
impl<S, T> FromRequestParts<S> for VldHeaders<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let value = headers_to_json(
parts
.headers
.iter()
.map(|(n, v)| (n.as_str(), v.as_bytes())),
);
validate(&value).map(VldHeaders)
}
}
pub struct VldCookie<T>(pub T);
impl<S, T> FromRequestParts<S> for VldCookie<T>
where
S: Send + Sync,
T: VldParse,
{
type Rejection = VldJsonRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let value = cookie_headers_to_json(
parts
.headers
.get_all(header::COOKIE)
.iter()
.map(|v| v.as_bytes()),
);
validate(&value).map(VldCookie)
}
}
crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
pub mod prelude {
pub use super::{VldCookie, VldForm, VldHeaders, VldJson, VldJsonRejection, VldPath, VldQuery};
pub use vld::prelude::*;
}