Skip to main content

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

1use super::BytesRejection;
2use crate::Request;
3use crate::body::util::BodyExt;
4use crate::service::web::extract::FromRequest;
5use crate::utils::macros::{composite_http_rejection, define_http_rejection};
6use rama_utils::macros::impl_deref;
7
8/// Extractor to get the response body, collected as [`String`].
9#[derive(Debug, Clone)]
10pub struct Text(pub String);
11
12impl_deref!(Text: String);
13
14define_http_rejection! {
15    #[status = UNSUPPORTED_MEDIA_TYPE]
16    #[body = "Text requests must have `Content-Type: text/plain`"]
17    /// Rejection type for [`Text`]
18    /// used if the `Content-Type` header is missing
19    /// or its value is not `text/plain`.
20    pub struct InvalidTextContentType;
21}
22
23define_http_rejection! {
24    #[status = BAD_REQUEST]
25    #[body = "Failed to decode text payload"]
26    /// Rejection type used if the [`Text`]
27    /// was not valid UTF-8.
28    pub struct InvalidUtf8Text(Error);
29}
30
31composite_http_rejection! {
32    /// Rejection used for [`Text`]
33    ///
34    /// Contains one variant for each way the [`Text`] extractor
35    /// can fail.
36    pub enum TextRejection {
37        InvalidTextContentType,
38        InvalidUtf8Text,
39        BytesRejection,
40    }
41}
42
43impl FromRequest for Text {
44    type Rejection = TextRejection;
45
46    async fn from_request(req: Request) -> Result<Self, Self::Rejection> {
47        if !crate::service::web::extract::has_any_content_type(
48            req.headers(),
49            &[&crate::mime::TEXT_PLAIN],
50        ) {
51            return Err(InvalidTextContentType.into());
52        }
53
54        let body = req.into_body();
55        match body.collect().await {
56            Ok(c) => match String::from_utf8(c.to_bytes().to_vec()) {
57                Ok(s) => Ok(Self(s)),
58                Err(err) => Err(InvalidUtf8Text::from_err(err).into()),
59            },
60            Err(err) => Err(BytesRejection::from_err(err).into()),
61        }
62    }
63}
64
65#[cfg(test)]
66mod test {
67    use super::*;
68    use crate::service::web::WebService;
69    use crate::{Method, Request, StatusCode, header};
70    use rama_core::Service;
71
72    #[tokio::test]
73    async fn test_text() {
74        let service = WebService::default().with_post("/", async |Text(body): Text| {
75            assert_eq!(body, "test");
76        });
77
78        let req = Request::builder()
79            .method(Method::POST)
80            .header(header::CONTENT_TYPE, "text/plain")
81            .body("test".into())
82            .unwrap();
83        let resp = service.serve(req).await.unwrap();
84        assert_eq!(resp.status(), StatusCode::OK);
85    }
86
87    #[tokio::test]
88    async fn test_text_missing_content_type() {
89        let service = WebService::default().with_post("/", async |Text(_): Text| StatusCode::OK);
90
91        let req = Request::builder()
92            .method(Method::POST)
93            .body("test".into())
94            .unwrap();
95        let resp = service.serve(req).await.unwrap();
96        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
97    }
98
99    #[tokio::test]
100    async fn test_text_incorrect_content_type() {
101        let service = WebService::default().with_post("/", async |Text(_): Text| StatusCode::OK);
102
103        let req = Request::builder()
104            .method(Method::POST)
105            .header(header::CONTENT_TYPE, "application/json")
106            .body("test".into())
107            .unwrap();
108        let resp = service.serve(req).await.unwrap();
109        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
110    }
111
112    #[tokio::test]
113    async fn test_text_invalid_utf8() {
114        let service = WebService::default().with_post("/", async |Text(_): Text| StatusCode::OK);
115
116        let req = Request::builder()
117            .method(Method::POST)
118            .header(header::CONTENT_TYPE, "text/plain")
119            .body(vec![0, 159, 146, 150].into())
120            .unwrap();
121        let resp = service.serve(req).await.unwrap();
122        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
123    }
124}