poem_openapi/types/external/
string.rs1use 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 match HeaderValue::from_str(self) {
80 Ok(value) => Some(value),
81 Err(_) => None,
82 }
83 }
84}
85
86impl Type for &str {
87 const IS_REQUIRED: bool = true;
88
89 type RawValueType = Self;
90
91 type RawElementValueType = Self;
92
93 fn name() -> Cow<'static, str> {
94 "string".into()
95 }
96
97 fn schema_ref() -> MetaSchemaRef {
98 MetaSchemaRef::Inline(Box::new(MetaSchema::new("string")))
99 }
100
101 fn as_raw_value(&self) -> Option<&Self::RawValueType> {
102 Some(self)
103 }
104
105 fn raw_element_iter<'b>(
106 &'b self,
107 ) -> Box<dyn Iterator<Item = &'b Self::RawElementValueType> + 'b> {
108 Box::new(self.as_raw_value().into_iter())
109 }
110}
111
112impl ToJSON for &str {
113 fn to_json(&self) -> Option<Value> {
114 Some(Value::String(self.to_string()))
115 }
116}