1.7 KiB · text History 263b40b
//! A `Json` extractor whose rejections use the API's error envelope
//! (party-slut's `src/api/json.rs`): axum's own answers a malformed body with
//! plain text, which the app would fail to parse as an error.
use axum::extract::{FromRequest, Request};
use serde::de::DeserializeOwned;

use super::ApiError;

pub struct ApiJson<T>(pub T);

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

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        match axum::Json::<T>::from_request(req, state).await {
            Ok(axum::Json(value)) => Ok(ApiJson(value)),
            Err(rejection) => Err(ApiError::new(
                rejection.status(),
                "bad_request",
                "That request couldn't be read.",
            )
            .with_details(serde_json::json!({ "reason": rejection.body_text() }))),
        }
    }
}

/// A `Path` extractor whose rejections (a malformed id) use the envelope.
pub struct ApiPath<T>(pub T);

impl<T, S> axum::extract::FromRequestParts<S> for ApiPath<T>
where
    T: DeserializeOwned + Send,
    S: Send + Sync,
{
    type Rejection = ApiError;

    async fn from_request_parts(parts: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {
        match axum::extract::Path::<T>::from_request_parts(parts, state).await {
            Ok(axum::extract::Path(value)) => Ok(ApiPath(value)),
            Err(rejection) => Err(ApiError::new(rejection.status(), "bad_request", "That address isn't one this API knows.")
                .with_details(serde_json::json!({ "reason": rejection.body_text() }))),
        }
    }
}