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
//! This module is for transform functions and utilities that can be
//! applied to OpenApi specifications.

use std::mem;

use super::{
    definition::{
        Components, MediaType, OpenApi, Operation, ParameterValue, PathItem, RefOr, Response,
    },
    definition_ext::OperationMethod,
};
use schemars::{gen::SchemaSettings, schema::Schema, JsonSchema, Map};
use serde::Serialize;

#[derive(Debug)]
pub enum Error {
    SerdeJson(serde_json::Error),
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::SerdeJson(e) => e.fmt(f),
        }
    }
}

impl std::error::Error for Error {}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Error::SerdeJson(e)
    }
}

/// Sets the default response for all operations that don't yet have one.
///
/// Panics if the value cannot be JSON serialized.
pub fn default_response<D, R>(description: D, value: R) -> impl FnOnce(OpenApi) -> OpenApi
where
    D: ToString,
    R: JsonSchema + Serialize,
{
    default_response_when(description, value, |(_, _, _, o)| {
        o.responses.default.is_none()
    })
}

/// Sets the default response for operations that match the predicate.
///
/// Panics if the value cannot be JSON serialized.
pub fn default_response_when<D, R, P>(
    description: D,
    value: R,
    predicate: P,
) -> impl FnOnce(OpenApi) -> OpenApi
where
    D: ToString,
    R: JsonSchema + Serialize,
    P: Fn((&String, &PathItem, OperationMethod, &Operation)) -> bool,
{
    move |mut spec: OpenApi| {
        let defs = spec
            .components
            .as_mut()
            .map(|c| mem::take(&mut c.schemas))
            .unwrap_or_default();

        let mut gen = SchemaSettings::openapi3()
            .into_generator()
            .with_definitions(
                defs.into_iter()
                    .map(|(name, o)| (name, Schema::Object(o)))
                    .collect(),
            );

        let s = gen.subschema_for::<R>().into_object();

        match &mut spec.components {
            Some(c) => {
                c.schemas = gen
                    .take_definitions()
                    .into_iter()
                    .map(|(name, s)| (name, s.into_object()))
                    .collect();
            }
            None => {
                let mut c = Components::default();
                c.schemas = gen
                    .take_definitions()
                    .into_iter()
                    .map(|(name, s)| (name, s.into_object()))
                    .collect();
                spec.components = c.into();
            }
        }

        let ex = serde_json::to_value(value).unwrap();

        for (path, pt) in &mut spec.paths {
            // This is done this way because the of the mutable and
            // immutable borrows of the PathItem.
            let mut methods: Vec<OperationMethod> = Vec::new();

            for (om, op) in pt.operations() {
                if predicate((path, pt, om, op)) {
                    methods.push(om);
                }
            }

            for om in methods {
                pt.operation_mut(om).as_mut().unwrap().responses.default =
                    Some(RefOr::Object(Response {
                        description: description.to_string(),
                        content: {
                            let mut m = Map::new();
                            m.insert(
                                "application/json".into(),
                                MediaType {
                                    schema: Some(s.clone()),
                                    example: Some(ex.clone()),
                                    ..Default::default()
                                },
                            );
                            m
                        },
                        ..Default::default()
                    }));
            }
        }

        spec
    }
}

/// Removes the nullable property from parameters.
pub fn remove_parameter_nullable(mut spec: OpenApi) -> OpenApi {
    for (_, pt) in &mut spec.paths {
        for (_, op) in pt.operations_mut() {
            if let Some(op) = op {
                for param in &mut op.parameters {
                    match param {
                        RefOr::Ref(_) => { /* we don't touch it, as it can used anywhere else */ }
                        RefOr::Object(p) => match &mut p.value {
                            ParameterValue::Schema { schema, .. } => {
                                schema.extensions.remove("nullable");
                            }
                            ParameterValue::Content { content } => {
                                for (_, c) in content {
                                    match &mut c.schema {
                                        Some(s) => {
                                            s.extensions.remove("nullable");
                                        }
                                        None => {}
                                    }
                                }
                            }
                        },
                    }
                }
            }
        }
    }

    spec
}