Skip to main content

openapi_nexus_spec/oas31/spec/
example.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use super::{ErrorRef, FromRef, OpenApiV31Spec, Ref, RefType, spec_extensions};
6
7/// Multi-purpose example objects.
8#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
9pub struct Example {
10    #[serde(skip_serializing_if = "Option::is_none")]
11    pub summary: Option<String>,
12
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub description: Option<String>,
15
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub value: Option<serde_json::Value>,
18
19    #[serde(flatten, with = "spec_extensions")]
20    pub extensions: BTreeMap<String, serde_json::Value>,
21}
22
23impl Example {
24    /// Returns JSON-encoded bytes of this example's value.
25    pub fn as_bytes(&self) -> Vec<u8> {
26        match self.value {
27            Some(ref val) => serde_json::to_string(val).unwrap().as_bytes().to_owned(),
28            None => vec![],
29        }
30    }
31}
32
33impl FromRef for Example {
34    fn from_ref(spec: &OpenApiV31Spec, path: &str) -> Result<Self, ErrorRef> {
35        let refpath = path.parse::<Ref>()?;
36
37        match refpath.kind {
38            RefType::Example => spec
39                .components
40                .as_ref()
41                .and_then(|cs| cs.examples.get(&refpath.name))
42                .ok_or_else(|| ErrorRef::Unresolvable {
43                    path: path.to_owned(),
44                })
45                .and_then(|oor| oor.resolve(spec)),
46
47            typ => Err(ErrorRef::MismatchedType {
48                expected: typ,
49                actual: RefType::Example,
50            }),
51        }
52    }
53}