Skip to main content

oas3/spec/
example.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use super::{spec_extensions, FromRef, Ref, RefError, RefType, Spec};
6
7/// Multi-purpose example objects.
8///
9/// Will be validated against schema when used in conformance testing.
10///
11/// See <https://spec.openapis.org/oas/v3.1.1#example-object>.
12#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
13pub struct Example {
14    /// Short description for the example.
15    #[serde(skip_serializing_if = "Option::is_none")]
16    pub summary: Option<String>,
17
18    /// Long description for the example.
19    /// [CommonMark syntax](https://spec.commonmark.org) MAY be used for rich text representation.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub description: Option<String>,
22
23    // FIXME: Implement (merge with externalValue as enum)
24    /// Embedded literal example. The `value` field and `externalValue` field are mutually
25    /// exclusive. To represent examples of media types that cannot naturally represented
26    /// in JSON or YAML, use a string value to contain the example, escaping where necessary.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub value: Option<serde_json::Value>,
29    //
30    // FIXME: Implement (merge with value as enum)
31    // /// A URL that points to the literal example. This provides the capability to reference
32    // /// examples that cannot easily be included in JSON or YAML documents. The `value` field
33    // /// and `externalValue` field are mutually exclusive.
34    // #[serde(skip_serializing_if = "Option::is_none")]
35    // pub externalValue: Option<String>,
36    //
37    /// Specification extensions.
38    ///
39    /// Only "x-" prefixed keys are collected, and the prefix is stripped.
40    ///
41    /// See <https://spec.openapis.org/oas/v3.1.1#specification-extensions>.
42    #[serde(flatten, with = "spec_extensions")]
43    pub extensions: BTreeMap<String, serde_json::Value>,
44}
45
46impl Example {
47    /// Returns JSON-encoded bytes of this example's value.
48    pub fn as_bytes(&self) -> Vec<u8> {
49        match self.value {
50            Some(ref val) => serde_json::to_string(val).unwrap().as_bytes().to_owned(),
51            None => vec![],
52        }
53    }
54}
55
56impl FromRef for Example {
57    fn from_ref(spec: &Spec, path: &str) -> Result<Self, RefError> {
58        let refpath = path.parse::<Ref>()?;
59
60        match refpath.kind {
61            RefType::Example => spec
62                .components
63                .as_ref()
64                .and_then(|cs| cs.examples.get(&refpath.name))
65                .ok_or_else(|| RefError::Unresolvable(path.to_owned()))
66                .and_then(|oor| oor.resolve(spec)),
67
68            typ => Err(RefError::MismatchedType(typ, RefType::Example)),
69        }
70    }
71}