poem_openapi/types/external/
string.rs

1use std::borrow::Cow;
2
3use poem::{http::HeaderValue, web::Field};
4use serde_json::Value;
5
6use crate::{
7    registry::{MetaSchema, MetaSchemaRef},
8    types::{
9        ParseError, ParseFromJSON, ParseFromMultipartField, ParseFromParameter, ParseResult,
10        ToHeader, ToJSON, Type,
11    },
12};
13
14impl Type for String {
15    const IS_REQUIRED: bool = true;
16
17    type RawValueType = Self;
18
19    type RawElementValueType = Self;
20
21    fn name() -> Cow<'static, str> {
22        "string".into()
23    }
24
25    fn schema_ref() -> MetaSchemaRef {
26        MetaSchemaRef::Inline(Box::new(MetaSchema::new("string")))
27    }
28
29    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
30        Some(self)
31    }
32
33    fn raw_element_iter<'a>(
34        &'a self,
35    ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
36        Box::new(self.as_raw_value().into_iter())
37    }
38
39    fn is_empty(&self) -> bool {
40        String::is_empty(self)
41    }
42}
43
44impl ParseFromJSON for String {
45    fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
46        let value = value.unwrap_or_default();
47        match value {
48            Value::String(val) => Ok(val),
49            Value::Number(num) => Ok(num.to_string()),
50            Value::Bool(val) => Ok(val.to_string()),
51            _ => Err(ParseError::expected_type(value)),
52        }
53    }
54}
55
56impl ParseFromParameter for String {
57    fn parse_from_parameter(value: &str) -> ParseResult<Self> {
58        Ok(value.to_string())
59    }
60}
61
62impl ParseFromMultipartField for String {
63    async fn parse_from_multipart(field: Option<Field>) -> ParseResult<Self> {
64        match field {
65            Some(field) => Ok(field.text().await.map_err(ParseError::custom)?),
66            None => Err(ParseError::expected_input()),
67        }
68    }
69}
70
71impl ToJSON for String {
72    fn to_json(&self) -> Option<Value> {
73        Some(Value::String(self.clone()))
74    }
75}
76
77impl ToHeader for String {
78    fn to_header(&self) -> Option<HeaderValue> {
79        HeaderValue::from_str(self).ok()
80    }
81}
82
83impl Type for &str {
84    const IS_REQUIRED: bool = true;
85
86    type RawValueType = Self;
87
88    type RawElementValueType = Self;
89
90    fn name() -> Cow<'static, str> {
91        "string".into()
92    }
93
94    fn schema_ref() -> MetaSchemaRef {
95        MetaSchemaRef::Inline(Box::new(MetaSchema::new("string")))
96    }
97
98    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
99        Some(self)
100    }
101
102    fn raw_element_iter<'b>(
103        &'b self,
104    ) -> Box<dyn Iterator<Item = &'b Self::RawElementValueType> + 'b> {
105        Box::new(self.as_raw_value().into_iter())
106    }
107}
108
109impl ToJSON for &str {
110    fn to_json(&self) -> Option<Value> {
111        Some(Value::String(self.to_string()))
112    }
113}