aboutsummaryrefslogtreecommitdiff
path: root/src/hyper_body.rs
blob: 74006333b19adce7ea1a72e2b1ef05f7aa233897 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! Extends `hyper::Body` with [`SputnikBody`].
use std::{future::Future, pin::Pin};

use hyper::http::{self, response::Builder};
use serde::de::DeserializeOwned;

use crate::response::EmptyBuilder;

impl EmptyBuilder<hyper::Body> for Builder {
    fn empty(self) -> http::Result<http::response::Response<hyper::Body>> {
        self.body(hyper::Body::empty())
    }
}

/// Adds deserialization methods to `hyper::Body`.
pub trait SputnikBody {
    /// Parses a `application/x-www-form-urlencoded` request body into a given struct.
    fn into_form<T: DeserializeOwned>(
        self,
    ) -> Pin<Box<dyn Future<Output = Result<T, FormError>> + Send + Sync>>;

    /// Attempts to deserialize the request body as JSON.
    #[cfg(feature = "hyper_body_json")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hyper_body_json")))]
    fn into_json<T: DeserializeOwned>(
        self,
    ) -> Pin<Box<dyn Future<Output = Result<T, JsonError>> + Send + Sync>>;
}

impl SputnikBody for hyper::Body {
    fn into_form<T: DeserializeOwned>(
        self,
    ) -> Pin<Box<dyn Future<Output = Result<T, FormError>> + Send + Sync>> {
        Box::pin(async move {
            let full_body = hyper::body::to_bytes(self).await.map_err(BodyError)?;
            Ok(serde_urlencoded::from_bytes::<T>(&full_body)?)
        })
    }

    #[cfg(feature = "hyper_body_json")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hyper_body_json")))]
    fn into_json<T: DeserializeOwned>(
        self,
    ) -> Pin<Box<dyn Future<Output = Result<T, JsonError>> + Send + Sync>> {
        Box::pin(async move {
            let full_body = hyper::body::to_bytes(self).await.map_err(BodyError)?;
            Ok(serde_json::from_slice::<T>(&full_body)?)
        })
    }
}

#[derive(thiserror::Error, Debug)]
#[error("failed to read body")]
pub struct BodyError(pub hyper::Error);

#[derive(thiserror::Error, Debug)]
pub enum FormError {
    #[error("{0}")]
    Body(#[from] BodyError),

    #[error("form deserialize error: {0}")]
    Deserialize(#[from] serde_urlencoded::de::Error),
}

#[cfg(feature = "hyper_body_json")]
#[cfg_attr(docsrs, doc(cfg(feature = "hyper_body_json")))]
#[derive(thiserror::Error, Debug)]
pub enum JsonError {
    #[error("{0}")]
    Body(#[from] BodyError),

    #[error("json deserialize error: {0}")]
    Deserialize(#[from] serde_json::Error),
}