poem_openapi/payload/
plain_text.rs

1use std::ops::{Deref, DerefMut};
2
3use poem::{FromRequest, IntoResponse, Request, RequestBody, Response, Result};
4
5use crate::{
6    payload::{ParsePayload, Payload},
7    registry::{MetaMediaType, MetaResponse, MetaResponses, MetaSchemaRef, Registry},
8    types::Type,
9    ApiResponse,
10};
11
12/// A UTF8 string payload.
13#[derive(Debug, Clone, Eq, PartialEq)]
14pub struct PlainText<T>(pub T);
15
16impl<T> Deref for PlainText<T> {
17    type Target = T;
18
19    fn deref(&self) -> &Self::Target {
20        &self.0
21    }
22}
23
24impl<T> DerefMut for PlainText<T> {
25    fn deref_mut(&mut self) -> &mut Self::Target {
26        &mut self.0
27    }
28}
29
30impl<T: Send> Payload for PlainText<T> {
31    const CONTENT_TYPE: &'static str = "text/plain; charset=utf-8";
32
33    fn check_content_type(content_type: &str) -> bool {
34        matches!(content_type.parse::<mime::Mime>(), Ok(content_type) if content_type.type_() == "text"
35                && (content_type.subtype() == "plain"
36                || content_type
37                    .suffix()
38                    .is_some_and(|v| v == "plain")))
39    }
40
41    fn schema_ref() -> MetaSchemaRef {
42        String::schema_ref()
43    }
44}
45
46impl ParsePayload for PlainText<String> {
47    const IS_REQUIRED: bool = true;
48
49    async fn from_request(request: &Request, body: &mut RequestBody) -> Result<Self> {
50        Ok(Self(String::from_request(request, body).await?))
51    }
52}
53
54impl<T: Into<String> + Send> IntoResponse for PlainText<T> {
55    fn into_response(self) -> Response {
56        self.0.into().into_response()
57    }
58}
59
60impl<T: Into<String> + Send> ApiResponse for PlainText<T> {
61    fn meta() -> MetaResponses {
62        MetaResponses {
63            responses: vec![MetaResponse {
64                description: "",
65                status: Some(200),
66                status_range: None,
67                content: vec![MetaMediaType {
68                    content_type: Self::CONTENT_TYPE,
69                    schema: Self::schema_ref(),
70                }],
71                headers: vec![],
72            }],
73        }
74    }
75
76    fn register(_registry: &mut Registry) {}
77}
78
79impl_apirequest_for_payload!(PlainText<String>);