All Downloads are FREE. Search and download functionalities are using the official Maven repository.

rust-server.models.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
#![allow(unused_qualifications)]

use validator::Validate;

use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
{{! Don't "use" structs here - they can conflict with the names of models, and mean that the code won't compile }}
{{#models}}
{{#model}}

{{#description}}
/// {{{.}}}
{{/description}}
{{#isEnum}}
/// Enumeration of values.
/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]`
/// which helps with FFI.
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, Hash)]
#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))]{{#xmlName}}
#[serde(rename = "{{{.}}}")]{{/xmlName}}
pub enum {{{classname}}} {
{{#allowableValues}}
  {{#enumVars}}
    #[serde(rename = {{{value}}})]
    {{{name}}},
  {{/enumVars}}
{{/allowableValues}}
}

impl std::fmt::Display for {{{classname}}} {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
{{#allowableValues}}
  {{#enumVars}}
            {{{classname}}}::{{{name}}} => write!(f, {{{value}}}),
  {{/enumVars}}
{{/allowableValues}}
        }
    }
}

impl std::str::FromStr for {{{classname}}} {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result {
        match s {
{{#allowableValues}}
  {{#enumVars}}
            {{{value}}} => std::result::Result::Ok({{{classname}}}::{{{name}}}),
  {{/enumVars}}
{{/allowableValues}}
            _ => std::result::Result::Err(format!("Value not valid: {}", s)),
        }
    }
}
{{/isEnum}}
{{^isEnum}}
{{#dataType}}
#[derive(Debug, Clone, PartialEq, {{#vendorExtensions.x-partial-ord}}PartialOrd, {{/vendorExtensions.x-partial-ord}}serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
{{#xmlName}}
#[serde(rename = "{{{.}}}")]
{{/xmlName}}
pub struct {{{classname}}}({{{dataType}}});

impl std::convert::From<{{{dataType}}}> for {{{classname}}} {
    fn from(x: {{{dataType}}}) -> Self {
        {{{classname}}}(x)
    }
}

impl std::convert::From<{{{classname}}}> for {{{dataType}}} {
    fn from(x: {{{classname}}}) -> Self {
        x.0
    }
}

impl std::ops::Deref for {{{classname}}} {
    type Target = {{{dataType}}};
    fn deref(&self) -> &{{{dataType}}} {
        &self.0
    }
}

impl std::ops::DerefMut for {{{classname}}} {
    fn deref_mut(&mut self) -> &mut {{{dataType}}} {
        &mut self.0
    }
}

{{#vendorExtensions.x-to-string-support}}
{{#vendorExtensions.x-is-string}}
impl std::string::ToString for {{{classname}}} {
    fn to_string(&self) -> String {
       self.0.clone()
    }
}

impl std::str::FromStr for {{{classname}}} {
    type Err = ::std::convert::Infallible;
    fn from_str(x: &str) -> std::result::Result {
        std::result::Result::Ok({{{classname}}}(x.to_owned()))
    }
}
{{/vendorExtensions.x-is-string}}
{{^vendorExtensions.x-is-string}}
/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl ::std::string::ToString for {{{classname}}} {
    fn to_string(&self) -> String {
        self.0.to_string()
    }
}

/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl ::std::str::FromStr for {{{classname}}} {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result {
        match std::str::FromStr::from_str(s) {
             std::result::Result::Ok(r) => std::result::Result::Ok({{{classname}}}(r)),
             std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to {{{classname}}}: {:?}", s, e)),
        }
    }
}
{{/vendorExtensions.x-is-string}}
{{/vendorExtensions.x-to-string-support}}
{{^vendorExtensions.x-to-string-support}}
/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl ::std::string::ToString for {{{classname}}} {
    fn to_string(&self) -> String {
        // ToString for this model is not supported
        "".to_string()
    }
}

/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl ::std::str::FromStr for {{{classname}}} {
    type Err = &'static str;

    fn from_str(s: &str) -> std::result::Result {
        std::result::Result::Err("Parsing {{{classname}}} is not supported")
    }
}
{{/vendorExtensions.x-to-string-support}}
{{/dataType}}
{{^dataType}}
{{#arrayModelType}}
{{#vendorExtensions}}{{#x-item-xml-name}}// Utility function for wrapping list elements when serializing xml
#[allow(non_snake_case)]
fn wrap_in_{{{x-item-xml-name}}}(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result
where
    S: serde::ser::Serializer,
{
    serde_xml_rs::wrap_primitives(item, serializer, "{{{x-item-xml-name}}}")
}

{{/x-item-xml-name}}
{{/vendorExtensions}}
{{! vec}}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct {{{classname}}}(
{{#vendorExtensions}}
{{#x-item-xml-name}}
    #[serde(serialize_with = "wrap_in_{{{x-item-xml-name}}}")]
{{/x-item-xml-name}}
{{/vendorExtensions}}
    Vec<{{{arrayModelType}}}>
);

impl std::convert::From> for {{{classname}}} {
    fn from(x: Vec<{{{arrayModelType}}}>) -> Self {
        {{{classname}}}(x)
    }
}

impl std::convert::From<{{{classname}}}> for Vec<{{{arrayModelType}}}> {
    fn from(x: {{{classname}}}) -> Self {
        x.0
    }
}

impl std::iter::FromIterator<{{{arrayModelType}}}> for {{{classname}}} {
    fn from_iter>(u: U) -> Self {
        {{{classname}}}(Vec::<{{{arrayModelType}}}>::from_iter(u))
    }
}

impl std::iter::IntoIterator for {{{classname}}} {
    type Item = {{{arrayModelType}}};
    type IntoIter = std::vec::IntoIter<{{{arrayModelType}}}>;

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

impl<'a> std::iter::IntoIterator for &'a {{{classname}}} {
    type Item = &'a {{{arrayModelType}}};
    type IntoIter = std::slice::Iter<'a, {{{arrayModelType}}}>;

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

impl<'a> std::iter::IntoIterator for &'a mut {{{classname}}} {
    type Item = &'a mut {{{arrayModelType}}};
    type IntoIter = std::slice::IterMut<'a, {{{arrayModelType}}}>;

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

impl std::ops::Deref for {{{classname}}} {
    type Target = Vec<{{{arrayModelType}}}>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

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

/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl std::string::ToString for {{{classname}}} {
    fn to_string(&self) -> String {
        self.iter().map(|x| x.to_string()).collect::>().join(",")
    }
}

/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl std::str::FromStr for {{{classname}}} {
    type Err = <{{{arrayModelType}}} as std::str::FromStr>::Err;

    fn from_str(s: &str) -> std::result::Result {
        let mut items = vec![];
        for item in s.split(',')
        {
            items.push(item.parse()?);
        }
        std::result::Result::Ok({{{classname}}}(items))
    }
}

{{/arrayModelType}}
{{^arrayModelType}}
{{! general struct}}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
{{#xmlName}}
#[serde(rename = "{{{.}}}")]
{{/xmlName}}
pub struct {{{classname}}} {
{{#vars}}{{#description}}    /// {{{.}}}
{{/description}}{{#isEnum}}    // Note: inline enums are not fully supported by openapi-generator
{{/isEnum}}
    #[serde(rename = "{{{baseName}}}")]
{{#vendorExtensions}}
{{#x-item-xml-name}}
    #[serde(serialize_with = "wrap_in_{{{x-item-xml-name}}}")]
{{/x-item-xml-name}}
{{/vendorExtensions}}
{{#hasValidation}}
    #[validate(
        {{#maxLength}}
            {{#minLength}}
            length(min = {{minLength}}, max = {{maxLength}}),
            {{/minLength}}
            {{^minLength}}
            length(max = {{maxLength}}),
            {{/minLength}}
        {{/maxLength}}
        {{^maxLength}}
            {{#minLength}}
            length(min = {{minLength}}),
            {{/minLength}}
        {{/maxLength}}
        {{#pattern}}
          {{^isByteArray}}
           regex = "RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}",
          {{/isByteArray}}
          {{#isByteArray}}
           custom ="validate_byte_{{#lambda.lowercase}}{{{classname}}}_{{{name}}}{{/lambda.lowercase}}"
          {{/isByteArray}}
        {{/pattern}}
        {{#maximum}}
            {{#minimum}}
            range(min = {{minimum}}, max = {{maximum}}),
            {{/minimum}}
            {{^minimum}}
            range(max = {{maximum}}),
            {{/minimum}}
        {{/maximum}}
        {{#minimum}}
            {{^maximum}}
            range(min = {{minimum}}),
            {{/maximum}}
        {{/minimum}}
        {{#maxItems}}
            {{#minItems}}
            length(min = {{minItems}}, max = {{maxItems}}),
            {{/minItems}}
            {{^minItems}}
            length(max = {{maxItems}}),
            {{/minItems}}
        {{/maxItems}}
        {{^maxItems}}
            {{#minItems}}
            length(min = {{minItems}}),
            {{/minItems}}
        {{/maxItems}}
        )]
{{/hasValidation}}
{{#required}}
    pub {{{name}}}: {{{dataType}}},
{{/required}}
{{^required}}
{{#isNullable}}
    #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")]
    #[serde(default = "swagger::nullable_format::default_optional_nullable")]
{{/isNullable}}
    #[serde(skip_serializing_if="Option::is_none")]
    pub {{{name}}}: Option<{{{dataType}}}>,
{{/required}}

{{/vars}}
}

{{#vars}}
{{#hasValidation}}
{{#pattern}}
{{^isByteArray}}
lazy_static::lazy_static! {
    static ref RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap();
}
{{/isByteArray}}
{{#isByteArray}}
lazy_static::lazy_static! {
    static ref RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap();
}
fn validate_byte_{{#lambda.lowercase}}{{{classname}}}_{{{name}}}{{/lambda.lowercase}}(
    b: &swagger::ByteArray
) -> Result<(), validator::ValidationError> {
    if !RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}.is_match(b) {
        return Err(validator::ValidationError::new("Character not allowed"));
    }
    Ok(())
}
{{/isByteArray}}
{{/pattern}}
{{/hasValidation}}
{{/vars}}

impl {{{classname}}} {
    #[allow(clippy::new_without_default)]
    pub fn new({{#vars}}{{^defaultValue}}{{{name}}}: {{{dataType}}}, {{/defaultValue}}{{/vars}}) -> {{{classname}}} {
        {{{classname}}} {
{{#vars}}            {{#defaultValue}}{{{name}}}: {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{{name}}}{{/defaultValue}},
{{/vars}}
        }
    }
}

/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false)
/// specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde serializer
impl std::string::ToString for {{{classname}}} {
    fn to_string(&self) -> String {
        let params: Vec> = vec![
{{#vars}}
{{#isByteArray}}
            // Skipping byte array {{baseName}} in query parameter serialization
{{/isByteArray}}
{{^isByteArray}}
{{#isBinary}}
            // Skipping binary data {{baseName}} in query parameter serialization
{{/isBinary}}
{{^isBinary}}
{{#isMap}}
            // Skipping map {{baseName}} in query parameter serialization
{{/isMap}}
{{^isMap}}
{{^isPrimitiveType}}
            // Skipping non-primitive type {{baseName}} in query parameter serialization
{{/isPrimitiveType}}
{{#isPrimitiveType}}
{{#required}}
            Some("{{{baseName}}}".to_string()),
{{^isArray}}
{{#isNullable}}
            Some(self.{{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string())),
{{/isNullable}}
{{^isNullable}}
            Some(self.{{{name}}}.to_string()),
{{/isNullable}}
{{/isArray}}
{{#isArray}}
{{#isNullable}}
            Some(self.{{{name}}}.as_ref().map_or(vec!["null".to_string()], |x| x.iter().map(|x| x.to_string()).collect::>().join(","))),
{{/isNullable}}
{{^isNullable}}
            Some(self.{{{name}}}.iter().map(|x| x.to_string()).collect::>().join(",")),
{{/isNullable}}
{{/isArray}}
{{/required}}
{{^required}}
            self.{{{name}}}.as_ref().map(|{{{name}}}| {
                [
                    "{{{baseName}}}".to_string(),
{{^isArray}}
{{#isNullable}}
                    {{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string()),
{{/isNullable}}
{{^isNullable}}
                    {{{name}}}.to_string(),
{{/isNullable}}
{{/isArray}}
{{#isArray}}
{{#isNullable}}
                    {{{name}}}.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")),
{{/isNullable}}
{{^isNullable}}
                    {{{name}}}.iter().map(|x| x.to_string()).collect::>().join(","),
{{/isNullable}}
{{/isArray}}
                ].join(",")
            }),
{{/required}}
{{/isPrimitiveType}}
{{/isMap}}
{{/isBinary}}
{{/isByteArray}}
{{/vars}}
        ];

        params.into_iter().flatten().collect::>().join(",")
    }
}

/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value
/// as specified in https://swagger.io/docs/specification/serialization/
/// Should be implemented in a serde deserializer
impl std::str::FromStr for {{{classname}}} {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result {
        /// An intermediate representation of the struct to use for parsing.
        #[derive(Default)]
        #[allow(dead_code)]
        struct IntermediateRep {
            {{#vars}}
            pub {{{name}}}: Vec<{{{dataType}}}>,
            {{/vars}}
        }

        let mut intermediate_rep = IntermediateRep::default();

        // Parse into intermediate representation
        let mut string_iter = s.split(',');
        let mut key_result = string_iter.next();

        while key_result.is_some() {
            let val = match string_iter.next() {
                Some(x) => x,
                None => return std::result::Result::Err("Missing value while parsing {{{classname}}}".to_string())
            };

            if let Some(key) = key_result {
                #[allow(clippy::match_single_binding)]
                match key {
          {{#vars}}
            {{#isBinary}}
                    "{{{baseName}}}" => return std::result::Result::Err("Parsing binary data in this style is not supported in {{{classname}}}".to_string()),
            {{/isBinary}}
            {{^isBinary}}
              {{#isByteArray}}
                    "{{{baseName}}}" => return std::result::Result::Err("Parsing binary data in this style is not supported in {{{classname}}}".to_string()),
              {{/isByteArray}}
              {{^isByteArray}}
                {{#isContainer}}
                    "{{{baseName}}}" => return std::result::Result::Err("Parsing a container in this style is not supported in {{{classname}}}".to_string()),
                {{/isContainer}}
                {{^isContainer}}
                  {{#isNullable}}
                    "{{{baseName}}}" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in {{{classname}}}".to_string()),
                  {{/isNullable}}
                  {{^isNullable}}
                    #[allow(clippy::redundant_clone)]
                    "{{{baseName}}}" => intermediate_rep.{{{name}}}.push(<{{{dataType}}} as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?),
                  {{/isNullable}}
                {{/isContainer}}
              {{/isByteArray}}
            {{/isBinary}}
          {{/vars}}
                    _ => return std::result::Result::Err("Unexpected key while parsing {{{classname}}}".to_string())
                }
            }

            // Get the next key
            key_result = string_iter.next();
        }

        // Use the intermediate representation to return the struct
        std::result::Result::Ok({{{classname}}} {
            {{#vars}}
            {{#isNullable}}
            {{{name}}}: std::result::Result::Err("Nullable types not supported in {{{classname}}}".to_string())?,
            {{/isNullable}}
            {{^isNullable}}
            {{{name}}}: intermediate_rep.{{{name}}}.into_iter().next(){{#required}}.ok_or_else(|| "{{{baseName}}} missing in {{{classname}}}".to_string())?{{/required}},
            {{/isNullable}}
            {{/vars}}
        })
    }
}
{{/arrayModelType}}
{{/dataType}}
{{/isEnum}}

// Methods for converting between header::IntoHeaderValue<{{{classname}}}> and hyper::header::HeaderValue

#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom> for hyper::header::HeaderValue {
    type Error = String;

    fn try_from(hdr_value: header::IntoHeaderValue<{{{classname}}}>) -> std::result::Result {
        let hdr_value = hdr_value.to_string();
        match hyper::header::HeaderValue::from_str(&hdr_value) {
             std::result::Result::Ok(value) => std::result::Result::Ok(value),
             std::result::Result::Err(e) => std::result::Result::Err(
                 format!("Invalid header value for {{classname}} - value: {} is invalid {}",
                     hdr_value, e))
        }
    }
}

#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom for header::IntoHeaderValue<{{{classname}}}> {
    type Error = String;

    fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result {
        match hdr_value.to_str() {
             std::result::Result::Ok(value) => {
                    match <{{{classname}}} as std::str::FromStr>::from_str(value) {
                        std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
                        std::result::Result::Err(err) => std::result::Result::Err(
                            format!("Unable to convert header value '{}' into {{classname}} - {}",
                                value, err))
                    }
             },
             std::result::Result::Err(e) => std::result::Result::Err(
                 format!("Unable to convert header: {:?} to string: {}",
                     hdr_value, e))
        }
    }
}

#[cfg(feature = "server")]
impl std::convert::TryFrom>> for hyper::header::HeaderValue {
    type Error = String;

    fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result {
        let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| {
            hdr_value.to_string()
        }).collect();

        match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) {
           std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value),
           std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}",
               hdr_values, e))
        }
    }
}

#[cfg(feature = "server")]
impl std::convert::TryFrom for header::IntoHeaderValue> {
    type Error = String;

    fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result {
        match hdr_values.to_str() {
            std::result::Result::Ok(hdr_values) => {
                let hdr_values : std::vec::Vec<{{{classname}}}> = hdr_values
                .split(',')
                .filter_map(|hdr_value| match hdr_value.trim() {
                    "" => std::option::Option::None,
                    hdr_value => std::option::Option::Some({
                        match <{{{classname}}} as std::str::FromStr>::from_str(hdr_value) {
                            std::result::Result::Ok(value) => std::result::Result::Ok(value),
                            std::result::Result::Err(err) => std::result::Result::Err(
                                format!("Unable to convert header value '{}' into {{classname}} - {}",
                                    hdr_value, err))
                        }
                    })
                }).collect::, String>>()?;

                std::result::Result::Ok(header::IntoHeaderValue(hdr_values))
            },
            std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}",
                hdr_values, e)),
        }
    }
}
{{#usesXml}}
{{#usesXmlNamespaces}}
{{#xmlNamespace}}

impl {{{classname}}} {
    /// Associated constant for this model's XML namespace.
    #[allow(dead_code)]
    pub const NAMESPACE: &'static str = "{{{xmlNamespace}}}";
}
{{/xmlNamespace}}
{{/usesXmlNamespaces}}

impl {{{classname}}} {
    /// Helper function to allow us to convert this model to an XML string.
    /// Will panic if serialisation fails.
    #[allow(dead_code)]
    pub(crate) fn as_xml(&self) -> String {
        {{#xmlNamespace}}
        let mut namespaces = std::collections::BTreeMap::new();
        // An empty string is used to indicate a global namespace in xmltree.
        namespaces.insert("".to_string(), Self::NAMESPACE.to_string());
        serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize")
        {{/xmlNamespace}}
        {{^xmlNamespace}}
        serde_xml_rs::to_string(&self).expect("impossible to fail to serialize")
        {{/xmlNamespace}}
    }
}
{{/usesXml}}
{{/model}}
{{/models}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy