poem_openapi/types/external/
uri.rs1use std::borrow::Cow;
2
3use poem::{
4 http::{HeaderValue, Uri},
5 web::Field,
6};
7use serde_json::Value;
8
9use crate::{
10 registry::{MetaSchema, MetaSchemaRef},
11 types::{
12 ParseError, ParseFromJSON, ParseFromMultipartField, ParseFromParameter, ParseResult,
13 ToHeader, ToJSON, Type,
14 },
15};
16
17impl Type for Uri {
18 const IS_REQUIRED: bool = true;
19
20 type RawValueType = Self;
21
22 type RawElementValueType = Self;
23
24 fn name() -> Cow<'static, str> {
25 "string_uri".into()
26 }
27
28 fn schema_ref() -> MetaSchemaRef {
29 MetaSchemaRef::Inline(Box::new(MetaSchema::new_with_format("string", "uri")))
30 }
31
32 fn as_raw_value(&self) -> Option<&Self::RawValueType> {
33 Some(self)
34 }
35
36 fn raw_element_iter<'a>(
37 &'a self,
38 ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
39 Box::new(self.as_raw_value().into_iter())
40 }
41}
42
43impl ParseFromJSON for Uri {
44 fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
45 let value = value.unwrap_or_default();
46 if let Value::String(value) = value {
47 Ok(value.parse()?)
48 } else {
49 Err(ParseError::expected_type(value))
50 }
51 }
52}
53
54impl ParseFromParameter for Uri {
55 fn parse_from_parameter(value: &str) -> ParseResult<Self> {
56 value.parse().map_err(ParseError::custom)
57 }
58}
59
60impl ParseFromMultipartField for Uri {
61 async fn parse_from_multipart(field: Option<Field>) -> ParseResult<Self> {
62 match field {
63 Some(field) => Ok(field.text().await?.parse()?),
64 None => Err(ParseError::expected_input()),
65 }
66 }
67}
68
69impl ToJSON for Uri {
70 fn to_json(&self) -> Option<Value> {
71 Some(Value::String(self.to_string()))
72 }
73}
74
75impl ToHeader for Uri {
76 fn to_header(&self) -> Option<HeaderValue> {
77 HeaderValue::from_str(&self.to_string()).ok()
78 }
79}