poem_openapi/types/external/
bson.rs1use std::borrow::Cow;
2
3use bson::oid::ObjectId;
4use poem::{http::HeaderValue, web::Field};
5use serde_json::Value;
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 ObjectId {
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_oid".into()
24 }
25
26 fn schema_ref() -> MetaSchemaRef {
27 MetaSchemaRef::Inline(Box::new(MetaSchema::new_with_format("string", "oid")))
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 ObjectId {
42 fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
43 let v: ObjectId = serde_json::from_value(value.unwrap_or_default())?;
44 Ok(v)
45 }
46}
47
48impl ParseFromParameter for ObjectId {
49 fn parse_from_parameter(value: &str) -> ParseResult<Self> {
50 ParseResult::Ok(ObjectId::parse_str(value)?)
51 }
52}
53
54impl ParseFromMultipartField for ObjectId {
55 async fn parse_from_multipart(field: Option<Field>) -> ParseResult<Self> {
56 match field {
57 Some(field) => Ok(ObjectId::parse_str(field.text().await?)?),
58 None => Err(ParseError::expected_input()),
59 }
60 }
61}
62
63impl ToJSON for ObjectId {
64 fn to_json(&self) -> Option<Value> {
65 serde_json::to_value(self).ok()
66 }
67}
68
69impl ToHeader for ObjectId {
70 fn to_header(&self) -> Option<HeaderValue> {
71 HeaderValue::from_str(&self.to_hex()).ok()
72 }
73}