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

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

There is a newer version: 7.9.0
Show newest version
            // {{{operationId}}} - {{{httpMethod}}} {{{path}}}
            hyper::Method::{{vendorExtensions.x-http-method}} if path.matched(paths::ID_{{vendorExtensions.x-path-id}}) => {
{{#hasAuthMethods}}
                {
                    let authorization = match *(&context as &dyn Has>).get() {
                        Some(ref authorization) => authorization,
                        None => return Ok(Response::builder()
                                                .status(StatusCode::FORBIDDEN)
                                                .body(Body::from("Unauthenticated"))
                                                .expect("Unable to create Authentication Forbidden response")),
                    };
                    {{#authMethods}}
                    {{#isOAuth}}

                    // Authorization
                    if let Scopes::Some(ref scopes) = authorization.scopes {
                        let required_scopes: std::collections::BTreeSet = vec![
                            {{#scopes}}
                            "{{{scope}}}".to_string(), // {{{description}}}
                            {{/scopes}}
                        ].into_iter().collect();

                        if !required_scopes.is_subset(scopes) {
                            let missing_scopes = required_scopes.difference(scopes);
                            return Ok(Response::builder()
                                .status(StatusCode::FORBIDDEN)
                                .body(Body::from(missing_scopes.fold(
                                    "Insufficient authorization, missing scopes".to_string(),
                                    |s, scope| format!("{} {}", s, scope))
                                ))
                                .expect("Unable to create Authentication Insufficient response")
                            );
                        }
                    }
                    {{/isOAuth}}
                    {{/authMethods}}
                }

{{/hasAuthMethods}}
{{#vendorExtensions}}
  {{#x-has-path-params}}
                // Path parameters
                let path: &str = uri.path();
                let path_params =
                    paths::REGEX_{{{x-path-id}}}
                    .captures(path)
                    .unwrap_or_else(||
                        panic!("Path {} matched RE {{{x-path-id}}} in set but failed match against \"{}\"", path, paths::REGEX_{{{x-path-id}}}.as_str())
                    );

  {{/x-has-path-params}}
{{/vendorExtensions}}
{{#pathParams}}
                let param_{{{paramName}}} = match percent_encoding::percent_decode(path_params["{{{baseName}}}"].as_bytes()).decode_utf8() {
                    Ok(param_{{{paramName}}}) => match param_{{{paramName}}}.parse::<{{{dataType}}}>() {
                        Ok(param_{{{paramName}}}) => param_{{{paramName}}},
                        Err(e) => return Ok(Response::builder()
                                        .status(StatusCode::BAD_REQUEST)
                                        .body(Body::from(format!("Couldn't parse path parameter {{{baseName}}}: {}", e)))
                                        .expect("Unable to create Bad Request response for invalid path parameter")),
                    },
                    Err(_) => return Ok(Response::builder()
                                        .status(StatusCode::BAD_REQUEST)
                                        .body(Body::from(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["{{{baseName}}}"])))
                                        .expect("Unable to create Bad Request response for invalid percent decode"))
                };

{{/pathParams}}
{{#vendorExtensions}}
  {{#x-callback-params}}
                let callback_{{.}} = path_params["{{{.}}}"].to_string();
  {{/x-callback-params}}
{{/vendorExtensions}}
{{#headerParams}}
  {{#-first}}
                // Header parameters
  {{/-first}}
                let param_{{{paramName}}} = headers.get(HeaderName::from_static("{{{nameInLowerCase}}}"));

                let param_{{{paramName}}} = match param_{{{paramName}}} {
                    Some(v) => match header::IntoHeaderValue::<{{{dataType}}}>::try_from((*v).clone()) {
                        Ok(result) =>
{{#required}}
                            result.0,
{{/required}}
{{^required}}
                            Some(result.0),
{{/required}}
                        Err(err) => {
                            return Ok(Response::builder()
                                        .status(StatusCode::BAD_REQUEST)
                                        .body(Body::from(format!("Invalid header {{{baseName}}} - {}", err)))
                                        .expect("Unable to create Bad Request response for invalid header {{{baseName}}}"));

                        },
                    },
                    None => {
{{#required}}
                        return Ok(Response::builder()
                                        .status(StatusCode::BAD_REQUEST)
                                        .body(Body::from("Missing required header {{{baseName}}}"))
                                        .expect("Unable to create Bad Request response for missing required header {{{baseName}}}"));
{{/required}}
{{^required}}
                        None
{{/required}}
                    }
                };
  {{#-last}}

  {{/-last}}
{{/headerParams}}
{{#queryParams}}
  {{#-first}}
                // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
                let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>();
  {{/-first}}
                let param_{{{paramName}}} = query_params.iter().filter(|e| e.0 == "{{{baseName}}}").map(|e| e.1.clone())
  {{#isArray}}
    {{^vendorExtensions.x-consumes-json}}
                    .filter_map(|param_{{{paramName}}}| param_{{{paramName}}}.parse().ok())
                    .collect::>();
      {{^required}}
                let param_{{{paramName}}} = if !param_{{{paramName}}}.is_empty() {
                    Some(param_{{{paramName}}})
                } else {
                    None
                };
      {{/required}}
    {{/vendorExtensions.x-consumes-json}}
    {{#vendorExtensions.x-consumes-json}}
                    .next();
                let param_{{{paramName}}} = match param_{{{paramName}}} {
                    Some(param_{{{paramName}}}) => {
                        let param_{{{paramName}}} =
                            serde_json::from_str::<{{{dataType}}}>
                                (¶m_{{{paramName}}});
                        match param_{{{paramName}}} {
                            Ok(param_{{{paramName}}}) => Some(param_{{{paramName}}}),
                            Err(e) => return Ok(Response::builder()
                                .status(StatusCode::BAD_REQUEST)
                                .body(Body::from(format!("Couldn't parse query parameter {{{baseName}}} - doesn't match schema: {}", e)))
                                .expect("Unable to create Bad Request response for invalid query parameter {{{baseName}}}")),
                        }
                    },
                    None => None,
                };
      {{#required}}
                let param_{{{paramName}}} = match param_{{{paramName}}} {
                    Some(param_{{{paramName}}}) => param_{{{paramName}}},
                    None => return Ok(Response::builder()
                        .status(StatusCode::BAD_REQUEST)
                        .body(Body::from("Missing required query parameter {{{baseName}}}"))
                        .expect("Unable to create Bad Request response for missing query parameter {{{baseName}}}")),
                };
      {{/required}}
    {{/vendorExtensions.x-consumes-json}}
  {{/isArray}}
  {{^isArray}}
                    .next();
                let param_{{{paramName}}} = match param_{{{paramName}}} {
                    Some(param_{{{paramName}}}) => {
                        let param_{{{paramName}}} =
    {{#vendorExtensions.x-consumes-json}}
                            serde_json::from_str::<{{{dataType}}}>
    {{/vendorExtensions.x-consumes-json}}
    {{^vendorExtensions.x-consumes-json}}
                            <{{{dataType}}} as std::str::FromStr>::from_str
    {{/vendorExtensions.x-consumes-json}}
                                (¶m_{{{paramName}}});
                        match param_{{{paramName}}} {
                            Ok(param_{{{paramName}}}) => Some(param_{{{paramName}}}),
                            Err(e) => return Ok(Response::builder()
                                .status(StatusCode::BAD_REQUEST)
                                .body(Body::from(format!("Couldn't parse query parameter {{{baseName}}} - doesn't match schema: {}", e)))
                                .expect("Unable to create Bad Request response for invalid query parameter {{{baseName}}}")),
                        }
                    },
                    None => None,
                };
    {{#required}}
                let param_{{{paramName}}} = match param_{{{paramName}}} {
                    Some(param_{{{paramName}}}) => param_{{{paramName}}},
                    None => return Ok(Response::builder()
                        .status(StatusCode::BAD_REQUEST)
                        .body(Body::from("Missing required query parameter {{{baseName}}}"))
                        .expect("Unable to create Bad Request response for missing query parameter {{{baseName}}}")),
                };
    {{/required}}
  {{/isArray}}
  {{#-last}}

  {{/-last}}
{{/queryParams}}
{{#vendorExtensions.x-has-request-body}}
                // Handle body parameters (note that non-required body parameters will ignore garbage
                // values, rather than causing a 400 response). Produce warning header and logs for
                // any unused fields.
                let result = body.into_raw().await;
                match result {
                     Ok(body) => {
  {{^vendorExtensions.x-consumes-multipart-form}}
    {{^vendorExtensions.x-consumes-form}}
      {{^bodyParam.vendorExtensions.x-consumes-plain-text}}
                                let mut unused_elements : Vec = vec![];
      {{/bodyParam.vendorExtensions.x-consumes-plain-text}}
    {{/vendorExtensions.x-consumes-form}}
  {{/vendorExtensions.x-consumes-multipart-form}}
{{>server-request-body-instance}}
{{/vendorExtensions.x-has-request-body}}
                                let result = api_impl.{{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}(
                                        {{#vendorExtensions}}
                                          {{#x-callback-params}}
                                            callback_{{.}},
                                          {{/x-callback-params}}
                                        {{/vendorExtensions}}
                                        {{#allParams}}
                                            param_{{{paramName}}}{{#isArray}}.as_ref(){{/isArray}},
                                        {{/allParams}}
                                        &context
                                    ).await;
                                let mut response = Response::new(Body::empty());
                                response.headers_mut().insert(
                                            HeaderName::from_static("x-span-id"),
                                            HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str())
                                                .expect("Unable to create X-Span-ID header value"));

{{#vendorExtensions.x-has-request-body}}
  {{^vendorExtensions.x-consumes-multipart-form}}
    {{^vendorExtensions.x-consumes-form}}
      {{^bodyParam.vendorExtensions.x-consumes-plain-text}}
                                        if !unused_elements.is_empty() {
                                            response.headers_mut().insert(
                                                HeaderName::from_static("warning"),
                                                HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str())
                                                    .expect("Unable to create Warning header value"));
                                        }
      {{/bodyParam.vendorExtensions.x-consumes-plain-text}}
    {{/vendorExtensions.x-consumes-form}}
  {{/vendorExtensions.x-consumes-multipart-form}}
{{/vendorExtensions.x-has-request-body}}
                                        match result {
                                            Ok(rsp) => match rsp {
{{#responses}}
                                                {{{operationId}}}Response::{{#vendorExtensions}}{{x-response-id}}{{/vendorExtensions}}
{{#dataType}}
{{^headers}}
                                                    (body)
{{/headers}}
{{#headers}}
{{#-first}}
                                                    {
                                                        body,
{{/-first}}
                                                        {{{name}}}{{^-last}},{{/-last}}
{{#-last}}
                                                    }
{{/-last}}
{{/headers}}
{{/dataType}}
{{^dataType}}
{{#headers}}
{{#-first}}
                                                    {
{{/-first}}
                                                        {{{name}}}{{^-last}},{{/-last}}
{{#-last}}
                                                    }
{{/-last}}
{{/headers}}
{{/dataType}}
                                                => {
                                                    *response.status_mut() = StatusCode::from_u16({{{code}}}).expect("Unable to turn {{{code}}} into a StatusCode");
{{#headers}}

  {{^required}}
                                                    if let Some({{{name}}}) = {{{name}}} {
  {{/required}}
                                                    let {{{name}}} = match header::IntoHeaderValue({{{name}}}).try_into() {
                                                        Ok(val) => val,
                                                        Err(e) => {
                                                            return Ok(Response::builder()
                                                                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                                                                    .body(Body::from(format!("An internal server error occurred handling {{name}} header - {}", e)))
                                                                    .expect("Unable to create Internal Server Error for invalid response header"))
                                                        }
                                                    };

                                                    response.headers_mut().insert(
                                                        HeaderName::from_static("{{{nameInLowerCase}}}"),
                                                        {{name}}
                                                    );
  {{^required}}
                                                    }
  {{/required}}
{{/headers}}
{{>server-response-body-instance}}
                                                },
{{/responses}}
                                            },
                                            Err(_) => {
                                                // Application code returned an error. This should not happen, as the implementation should
                                                // return a valid response.
                                                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                                                *response.body_mut() = Body::from("An internal error occurred");
                                            },
                                        }

                                        Ok(response)
{{#vendorExtensions.x-has-request-body}}
                            },
                            Err(e) => Ok(Response::builder()
                                                .status(StatusCode::BAD_REQUEST)
                                                .body(Body::from(format!("Unable to read body: {}", e)))
                                                .expect("Unable to create Bad Request response due to unable to read body")),
                        }
{{/vendorExtensions.x-has-request-body}}
            },




© 2015 - 2024 Weber Informatics LLC | Privacy Policy