poem_openapi/types/external/
uuid.rs

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