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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Implements [OpenApi Responses][responses].
//!
//! [responses]: https://spec.openapis.org/oas/latest.html#responses-object
use std::ops::{Deref, DerefMut};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::{PropMap, Ref, RefOr};

use super::link::Link;
use super::{header::Header, Content};

/// Implements [OpenAPI Responses Object][responses].
///
/// Responses is a map holding api operation responses identified by their status code.
///
/// [responses]: https://spec.openapis.org/oas/latest.html#responses-object
#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Responses(PropMap<String, RefOr<Response>>);

impl<K, R> From<PropMap<K, R>> for Responses
where
    K: Into<String>,
    R: Into<RefOr<Response>>,
{
    fn from(inner: PropMap<K, R>) -> Self {
        Self(
            inner
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        )
    }
}
impl<K, R, const N: usize> From<[(K, R); N]> for Responses
where
    K: Into<String>,
    R: Into<RefOr<Response>>,
{
    fn from(inner: [(K, R); N]) -> Self {
        Self(
            <[(K, R)]>::into_vec(Box::new(inner))
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        )
    }
}

impl Deref for Responses {
    type Target = PropMap<String, RefOr<Response>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Responses {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl IntoIterator for Responses {
    type Item = (String, RefOr<Response>);
    type IntoIter = <PropMap<String, RefOr<Response>> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl Responses {
    /// Construct a new empty [`Responses`]. This is effectively same as calling [`Responses::default`].
    pub fn new() -> Self {
        Default::default()
    }
    /// Inserts a key-value pair into the instance and retuns `self`.
    pub fn response<S: Into<String>, R: Into<RefOr<Response>>>(
        mut self,
        key: S,
        response: R,
    ) -> Self {
        self.insert(key, response);
        self
    }

    /// Inserts a key-value pair into the instance.
    pub fn insert<S: Into<String>, R: Into<RefOr<Response>>>(&mut self, key: S, response: R) {
        self.0.insert(key.into(), response.into());
    }

    /// Moves all elements from `other` into `self`, leaving `other` empty.
    ///
    /// If a key from `other` is already present in `self`, the respective
    /// value from `self` will be overwritten with the respective value from `other`.
    pub fn append(&mut self, other: &mut Responses) {
        self.0.append(&mut other.0);
    }

    /// Add responses from an iterator over a pair of `(status_code, response): (String, Response)`.
    pub fn extend<I, C, R>(&mut self, iter: I)
    where
        I: IntoIterator<Item = (C, R)>,
        C: Into<String>,
        R: Into<RefOr<Response>>,
    {
        self.0.extend(
            iter.into_iter()
                .map(|(key, response)| (key.into(), response.into())),
        );
    }
}

impl From<Responses> for PropMap<String, RefOr<Response>> {
    fn from(responses: Responses) -> Self {
        responses.0
    }
}

impl<C, R> FromIterator<(C, R)> for Responses
where
    C: Into<String>,
    R: Into<RefOr<Response>>,
{
    fn from_iter<T: IntoIterator<Item = (C, R)>>(iter: T) -> Self {
        Self(PropMap::from_iter(
            iter.into_iter()
                .map(|(key, response)| (key.into(), response.into())),
        ))
    }
}

/// Implements [OpenAPI Response Object][response].
///
/// Response is api operation response.
///
/// [response]: https://spec.openapis.org/oas/latest.html#response-object
#[non_exhaustive]
#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Response {
    /// Description of the response. Response support markdown syntax.
    pub description: String,

    /// Map of headers identified by their name. `Content-Type` header will be ignored.
    #[serde(skip_serializing_if = "PropMap::is_empty", default)]
    pub headers: PropMap<String, Header>,

    /// Map of response [`Content`] objects identified by response body content type e.g `application/json`.
    ///
    /// [`Content`]s are stored within [`IndexMap`] to retain their insertion order. Swagger UI
    /// will create and show default example according to the first entry in `content` map.
    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
    #[serde(rename = "content")]
    pub contents: IndexMap<String, Content>,

    /// Optional extensions "x-something"
    #[serde(skip_serializing_if = "PropMap::is_empty", flatten)]
    pub extensions: PropMap<String, serde_json::Value>,

    /// A map of operations links that can be followed from the response. The key of the
    /// map is a short name for the link.
    #[serde(skip_serializing_if = "PropMap::is_empty", default)]
    pub links: PropMap<String, RefOr<Link>>,
}

impl Response {
    /// Construct a new [`Response`].
    ///
    /// Function takes description as argument.
    pub fn new<S: Into<String>>(description: S) -> Self {
        Self {
            description: description.into(),
            ..Default::default()
        }
    }

    /// Add description. Description supports markdown syntax.
    pub fn description<I: Into<String>>(mut self, description: I) -> Self {
        self.description = description.into();
        self
    }

    /// Add [`Content`] of the [`Response`] with content type e.g `application/json` and returns `Self`.
    pub fn add_content<S: Into<String>, C: Into<Content>>(mut self, key: S, content: C) -> Self {
        self.contents.insert(key.into(), content.into());
        self
    }
    /// Add response [`Header`] and returns `Self`.
    pub fn add_header<S: Into<String>>(mut self, name: S, header: Header) -> Self {
        self.headers.insert(name.into(), header);
        self
    }

    /// Add openapi extension (`x-something`) for [`Response`].
    pub fn add_extension<K: Into<String>>(mut self, key: K, value: serde_json::Value) -> Self {
        self.extensions.insert(key.into(), value);
        self
    }

    /// Add link that can be followed from the response.
    pub fn add_link<S: Into<String>, L: Into<RefOr<Link>>>(mut self, name: S, link: L) -> Self {
        self.links.insert(name.into(), link.into());

        self
    }
}

impl From<Ref> for RefOr<Response> {
    fn from(r: Ref) -> Self {
        Self::Ref(r)
    }
}

#[cfg(test)]
mod tests {
    use super::{Content, Header, PropMap, Ref, RefOr, Response, Responses};
    use assert_json_diff::assert_json_eq;
    use serde_json::json;

    #[test]
    fn responses_new() {
        let responses = Responses::new();
        assert!(responses.is_empty());
    }

    #[test]
    fn response_builder() -> Result<(), serde_json::Error> {
        let request_body = Response::new("A sample response")
            .description("A sample response description")
            .add_content(
                "application/json",
                Content::new(Ref::from_schema_name("MySchemaPayload")),
            )
            .add_header(
                "content-type",
                Header::default().description("application/json"),
            );

        assert_json_eq!(
            request_body,
            json!({
              "description": "A sample response description",
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/MySchemaPayload"
                  }
                }
              },
              "headers": {
                "content-type": {
                  "description": "application/json",
                  "schema": {
                    "type": "string"
                  }
                }
              }
            })
        );
        Ok(())
    }

    #[test]
    fn test_responses_from_btree_map() {
        let input = PropMap::from([
            ("response1".to_string(), Response::new("response1")),
            ("response2".to_string(), Response::new("response2")),
        ]);

        let expected = Responses(PropMap::from([
            (
                "response1".to_string(),
                RefOr::Type(Response::new("response1")),
            ),
            (
                "response2".to_string(),
                RefOr::Type(Response::new("response2")),
            ),
        ]));

        let actual = Responses::from(input);

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_responses_from_kv_sequence() {
        let input = [
            ("response1".to_string(), Response::new("response1")),
            ("response2".to_string(), Response::new("response2")),
        ];

        let expected = Responses(PropMap::from([
            (
                "response1".to_string(),
                RefOr::Type(Response::new("response1")),
            ),
            (
                "response2".to_string(),
                RefOr::Type(Response::new("response2")),
            ),
        ]));

        let actual = Responses::from(input);

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_responses_from_iter() {
        let input = [
            ("response1".to_string(), Response::new("response1")),
            ("response2".to_string(), Response::new("response2")),
        ];

        let expected = Responses(PropMap::from([
            (
                "response1".to_string(),
                RefOr::Type(Response::new("response1")),
            ),
            (
                "response2".to_string(),
                RefOr::Type(Response::new("response2")),
            ),
        ]));

        let actual = Responses::from_iter(input);

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_responses_into_iter() {
        let responses = Responses::new();
        let responses = responses.response("response1", Response::new("response1"));
        assert_eq!(1, responses.into_iter().collect::<Vec<_>>().len());
    }

    #[test]
    fn test_btree_map_from_responses() {
        let expected = PropMap::from([
            (
                "response1".to_string(),
                RefOr::Type(Response::new("response1")),
            ),
            (
                "response2".to_string(),
                RefOr::Type(Response::new("response2")),
            ),
        ]);

        let actual = PropMap::from(
            Responses::new()
                .response("response1", Response::new("response1"))
                .response("response2", Response::new("response2")),
        );
        assert_eq!(expected, actual);
    }
}