Skip to main content

kynos_openapi/model/body/
mod.rs

1//! The Request Body, Media Type and Encoding Objects.
2
3pub mod encoding;
4pub mod media_type;
5pub mod mime_names;
6
7use serde::{Deserialize, Serialize};
8
9use crate::{
10    Map,
11    model::{body::media_type::MediaType, extensions::Extensions, schema::Schema},
12};
13
14/// A request body.
15#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
16pub struct RequestBody {
17    /// A description of the body. [CommonMark] syntax may be used.
18    ///
19    /// [CommonMark]: https://spec.commonmark.org/
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub description: Option<String>,
22
23    /// The body's representations, keyed by media type or media type range.
24    ///
25    /// More than one entry describes a body the server accepts in several
26    /// encodings.
27    pub content: Map<MediaType>,
28
29    /// Whether the body is mandatory. Defaults to `false`.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub required: Option<bool>,
32
33    /// Specification extensions.
34    #[serde(flatten)]
35    pub extensions: Extensions,
36}
37
38impl RequestBody {
39    /// Creates a required body with a single media type.
40    pub fn new(media_type: impl Into<String>, content: MediaType) -> Self {
41        let mut map = Map::new();
42        map.insert(media_type.into(), content);
43        Self {
44            content: map,
45            required: Some(true),
46            ..Self::default()
47        }
48    }
49
50    /// Creates a required `application/json` body.
51    #[must_use]
52    pub fn json(schema: Schema) -> Self {
53        Self::new(mime_names::APPLICATION_JSON, MediaType::new(schema))
54    }
55
56    /// Adds another representation of the same body.
57    #[must_use]
58    pub fn with_media_type(mut self, media_type: impl Into<String>, content: MediaType) -> Self {
59        self.content.insert(media_type.into(), content);
60        self
61    }
62
63    /// Marks the body optional.
64    #[must_use]
65    pub fn optional(mut self) -> Self {
66        self.required = Some(false);
67        self
68    }
69
70    /// Sets the description.
71    #[must_use]
72    pub fn with_description(mut self, description: impl Into<String>) -> Self {
73        self.description = Some(description.into());
74        self
75    }
76}
77
78#[cfg(test)]
79mod tests;