poem_openapi/types/multipart/
json.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::borrow::Cow;

use poem::web::Field as PoemField;
use serde_json::Value;

use crate::{
    registry::{MetaSchemaRef, Registry},
    types::{ParseError, ParseFromJSON, ParseFromMultipartField, ParseResult, ToJSON, Type},
};

/// A JSON type for multipart field.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct JsonField<T>(pub T);

impl<T: Type> Type for JsonField<T> {
    const IS_REQUIRED: bool = true;

    type RawValueType = T::RawValueType;

    type RawElementValueType = T::RawElementValueType;

    fn name() -> Cow<'static, str> {
        T::name()
    }

    #[inline]
    fn schema_ref() -> MetaSchemaRef {
        T::schema_ref()
    }

    fn register(registry: &mut Registry) {
        T::register(registry);
    }

    #[inline]
    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
        self.0.as_raw_value()
    }

    fn raw_element_iter<'a>(
        &'a self,
    ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
        self.0.raw_element_iter()
    }
}

impl<T: ParseFromJSON> ParseFromMultipartField for JsonField<T> {
    async fn parse_from_multipart(field: Option<PoemField>) -> ParseResult<Self> {
        let value = match field {
            Some(field) => {
                let data = field.bytes().await.map_err(ParseError::custom)?;
                serde_json::from_slice(&data).map_err(ParseError::custom)?
            }
            None => Value::Null,
        };
        Ok(Self(
            T::parse_from_json(Some(value)).map_err(ParseError::propagate)?,
        ))
    }
}

impl<T: ToJSON> ToJSON for JsonField<T> {
    fn to_json(&self) -> Option<Value> {
        self.0.to_json()
    }
}