rama_http/service/web/endpoint/extract/body/
text.rs

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use super::BytesRejection;
use crate::dep::http_body_util::BodyExt;
use crate::service::web::extract::FromRequest;
use crate::utils::macros::{composite_http_rejection, define_http_rejection};
use crate::Request;
use rama_utils::macros::impl_deref;

/// Extractor to get the response body, collected as [`String`].
#[derive(Debug, Clone)]
pub struct Text(pub String);

impl_deref!(Text: String);

define_http_rejection! {
    #[status = UNSUPPORTED_MEDIA_TYPE]
    #[body = "Text requests must have `Content-Type: text/plain`"]
    /// Rejection type for [`Text`]
    /// used if the `Content-Type` header is missing
    /// or its value is not `text/plain`.
    pub struct InvalidTextContentType;
}

define_http_rejection! {
    #[status = BAD_REQUEST]
    #[body = "Failed to decode text payload"]
    /// Rejection type used if the [`Text`]
    /// was not valid UTF-8.
    pub struct InvalidUtf8Text(Error);
}

composite_http_rejection! {
    /// Rejection used for [`Text`]
    ///
    /// Contains one variant for each way the [`Text`] extractor
    /// can fail.
    pub enum TextRejection {
        InvalidTextContentType,
        InvalidUtf8Text,
        BytesRejection,
    }
}

impl FromRequest for Text {
    type Rejection = TextRejection;

    async fn from_request(req: Request) -> Result<Self, Self::Rejection> {
        if !crate::service::web::extract::has_any_content_type(req.headers(), &[&mime::TEXT_PLAIN])
        {
            return Err(InvalidTextContentType.into());
        }

        let body = req.into_body();
        match body.collect().await {
            Ok(c) => match String::from_utf8(c.to_bytes().to_vec()) {
                Ok(s) => Ok(Self(s)),
                Err(err) => Err(InvalidUtf8Text::from_err(err).into()),
            },
            Err(err) => Err(BytesRejection::from_err(err).into()),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::service::web::WebService;
    use crate::{header, Method, Request, StatusCode};
    use rama_core::{Context, Service};

    #[tokio::test]
    async fn test_text() {
        let service = WebService::default().post("/", |Text(body): Text| async move {
            assert_eq!(body, "test");
        });

        let req = Request::builder()
            .method(Method::POST)
            .header(header::CONTENT_TYPE, "text/plain")
            .body("test".into())
            .unwrap();
        let resp = service.serve(Context::default(), req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_text_missing_content_type() {
        let service =
            WebService::default().post("/", |Text(_): Text| async move { StatusCode::OK });

        let req = Request::builder()
            .method(Method::POST)
            .body("test".into())
            .unwrap();
        let resp = service.serve(Context::default(), req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn test_text_incorrect_content_type() {
        let service =
            WebService::default().post("/", |Text(_): Text| async move { StatusCode::OK });

        let req = Request::builder()
            .method(Method::POST)
            .header(header::CONTENT_TYPE, "application/json")
            .body("test".into())
            .unwrap();
        let resp = service.serve(Context::default(), req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn test_text_invalid_utf8() {
        let service =
            WebService::default().post("/", |Text(_): Text| async move { StatusCode::OK });

        let req = Request::builder()
            .method(Method::POST)
            .header(header::CONTENT_TYPE, "text/plain")
            .body(vec![0, 159, 146, 150].into())
            .unwrap();
        let resp = service.serve(Context::default(), req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }
}