Skip to content

Commit

Permalink
[rust-axum] Split up api trait per tag (#18621)
Browse files Browse the repository at this point in the history
* [rust-axum] Feat: split up api trait per tag

* [rust-axum] Fix: missing types in api files

* [rust-axum] Fix: add samples output

* [rust-axum] Feat: handle mutli tagged operations

* [rust-axum] Fix: spacing between generated operations

* [rust-axum] Fix: coding standards
  • Loading branch information
kalvinpearce committed May 19, 2024
1 parent 57dceae commit e9f961e
Show file tree
Hide file tree
Showing 62 changed files with 3,285 additions and 3,131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public RustAxumServerCodegen() {

importMapping = new HashMap<>();
modelTemplateFiles.clear();
apiTemplateFiles.clear();
apiTemplateFiles.put("apis.mustache", ".rs");

// types
defaultIncludes = new HashSet<>(
Expand Down Expand Up @@ -240,6 +240,7 @@ public RustAxumServerCodegen() {
supportingFiles.add(new SupportingFile("types.mustache", "src", "types.rs"));
supportingFiles.add(new SupportingFile("header.mustache", "src", "header.rs"));
supportingFiles.add(new SupportingFile("server-mod.mustache", "src/server", "mod.rs"));
supportingFiles.add(new SupportingFile("apis-mod.mustache", apiPackage().replace('.', File.separatorChar), "mod.rs"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")
.doNotOverwrite());
}
Expand Down Expand Up @@ -320,7 +321,7 @@ private void setPackageVersion(String packageVersion) {

@Override
public String apiPackage() {
return apiPath;
return "src" + File.separator + "apis";
}

@Override
Expand Down Expand Up @@ -349,6 +350,11 @@ public String toApiName(String name) {
sanitizeIdentifier(name, CasingType.SNAKE_CASE, "api", "API", true);
}

@Override
public String toApiFilename(String name) {
return toApiName(name);
}

/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
Expand Down Expand Up @@ -565,6 +571,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation
@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap operationsMap, List<ModelMap> allModels) {
OperationMap operations = operationsMap.getOperations();
operations.put("classnamePascalCase", camelize(operations.getClassname()));
List<CodegenOperation> operationList = operations.getOperation();

for (CodegenOperation op : operationList) {
Expand Down Expand Up @@ -649,13 +656,23 @@ public boolean isDataTypeFile(final String dataType) {
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation
op, Map<String, List<CodegenOperation>> operations) {
// only generate operation for the first tag of the tags
// If more than one tag, combine into a single unique group
if (tag != null && op.tags.size() > 1) {
// Skip any tags other than the first one. This is because we
// override the tag with a combined version of all the tags.
String expectedTag = sanitizeTag(op.tags.get(0).getName());
if (!tag.equals(expectedTag)) {
LOGGER.info("generated skip additional tag `{}` with operationId={}", tag, op.operationId);
return;
}

// Get all tags sorted by name
final List<String> tags = op.tags.stream().map(t -> t.getName()).sorted().collect(Collectors.toList());
// Combine into a single group
final String combinedTag = tags.stream().collect(Collectors.joining("-"));
// Add to group
super.addOperationToGroup(combinedTag, resourcePath, operation, op, operations);
return;
}
super.addOperationToGroup(tag, resourcePath, operation, op, operations);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{{#apiInfo}}
{{#apis}}
pub mod {{classFilename}};
{{/apis}}
{{/apiInfo}}

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use async_trait::async_trait;
use axum::extract::*;
use axum_extra::extract::{CookieJar, Multipart};
use bytes::Bytes;
use http::Method;
use serde::{Deserialize, Serialize};

use crate::{models, types::*};

{{#operations}}
{{#operation}}
{{>response}}
{{/operation}}
{{/operations}}

{{#operations}}
/// {{classnamePascalCase}}
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait {{classnamePascalCase}} {
{{#operation}}
{{#summary}}
/// {{{.}}}.
///
{{/summary}}
{{#vendorExtensions}}
/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}}
async fn {{{x-operation-id}}}(
&self,
method: Method,
host: Host,
cookies: CookieJar,
{{#headerParams.size}}
header_params: models::{{{operationIdCamelCase}}}HeaderParams,
{{/headerParams.size}}
{{#pathParams.size}}
path_params: models::{{{operationIdCamelCase}}}PathParams,
{{/pathParams.size}}
{{#queryParams.size}}
query_params: models::{{{operationIdCamelCase}}}QueryParams,
{{/queryParams.size}}
{{^x-consumes-multipart-related}}
{{^x-consumes-multipart}}
{{#bodyParam}}
{{#vendorExtensions}}
{{^x-consumes-plain-text}}
body: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}},
{{/x-consumes-plain-text}}
{{#x-consumes-plain-text}}
{{#isString}}
body: String,
{{/isString}}
{{^isString}}
body: Bytes,
{{/isString}}
{{/x-consumes-plain-text}}
{{/vendorExtensions}}
{{/bodyParam}}
{{/x-consumes-multipart}}
{{/x-consumes-multipart-related}}
{{#x-consumes-multipart}}
body: Multipart,
{{/x-consumes-multipart}}
{{#x-consumes-multipart-related}}
body: axum::body::Body,
{{/x-consumes-multipart-related}}
) -> Result<{{{operationId}}}Response, String>;
{{/vendorExtensions}}
{{^-last}}

{{/-last}}
{{/operation}}
}
{{/operations}}
Original file line number Diff line number Diff line change
Expand Up @@ -14,98 +14,17 @@
clippy::too_many_arguments
)]

use async_trait::async_trait;
use axum::extract::*;
use axum_extra::extract::{CookieJar, Multipart};
use bytes::Bytes;
use http::Method;
use serde::{Deserialize, Serialize};

use types::*;

pub const BASE_PATH: &str = "{{{basePathWithoutHost}}}";
{{#appVersion}}
pub const API_VERSION: &str = "{{{.}}}";
{{/appVersion}}

{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
{{>response}}
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}

/// API
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait Api {
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}

{{#summary}}
/// {{{.}}}.
///
{{/summary}}
{{#vendorExtensions}}
/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}}
async fn {{{x-operation-id}}}(
&self,
method: Method,
host: Host,
cookies: CookieJar,
{{#headerParams.size}}
header_params: models::{{{operationIdCamelCase}}}HeaderParams,
{{/headerParams.size}}
{{#pathParams.size}}
path_params: models::{{{operationIdCamelCase}}}PathParams,
{{/pathParams.size}}
{{#queryParams.size}}
query_params: models::{{{operationIdCamelCase}}}QueryParams,
{{/queryParams.size}}
{{^x-consumes-multipart-related}}
{{^x-consumes-multipart}}
{{#bodyParam}}
{{#vendorExtensions}}
{{^x-consumes-plain-text}}
body: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}},
{{/x-consumes-plain-text}}
{{#x-consumes-plain-text}}
{{#isString}}
body: String,
{{/isString}}
{{^isString}}
body: Bytes,
{{/isString}}
{{/x-consumes-plain-text}}
{{/vendorExtensions}}
{{/bodyParam}}
{{/x-consumes-multipart}}
{{/x-consumes-multipart-related}}
{{#x-consumes-multipart}}
body: Multipart,
{{/x-consumes-multipart}}
{{#x-consumes-multipart-related}}
body: axum::body::Body,
{{/x-consumes-multipart-related}}
) -> Result<{{{operationId}}}Response, String>;
{{/vendorExtensions}}

{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
}

#[cfg(feature = "server")]
pub mod server;

pub mod models;
pub mod types;
pub mod apis;

#[cfg(feature = "server")]
pub(crate) mod header;
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ use validator::{Validate, ValidationErrors};
use crate::{header, types::*};

#[allow(unused_imports)]
use crate::models;
use crate::{apis, models};
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
{{>server-imports}}
use crate::{Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
};

{{>server-route}}
{{#apiInfo}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A>(
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: Api,
A: apis::{{classFilename}}::{{classnamePascalCase}},
{
{{#headerParams}}
{{#-first}}
Expand Down Expand Up @@ -187,7 +187,7 @@ where
let resp = match result {
Ok(rsp) => match rsp {
{{#responses}}
{{{operationId}}}Response::{{#vendorExtensions}}{{x-response-id}}{{/vendorExtensions}}
apis::{{classFilename}}::{{{operationId}}}Response::{{#vendorExtensions}}{{x-response-id}}{{/vendorExtensions}}
{{#dataType}}
{{^headers}}
(body)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pub fn new<I, A>(api_impl: I) -> Router
where
I: AsRef<A> + Clone + Send + Sync + 'static,
A: Api + 'static,
A: {{#apiInfo}}{{#apis}}{{#operations}}apis::{{classFilename}}::{{classnamePascalCase}} + {{/operations}}{{/apis}}{{/apiInfo}}'static,
{
// build our application with a route
Router::new()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
.gitignore
Cargo.toml
README.md
src/apis/default.rs
src/apis/mod.rs
src/header.rs
src/lib.rs
src/models.rs
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use async_trait::async_trait;
use axum::extract::*;
use axum_extra::extract::{CookieJar, Multipart};
use bytes::Bytes;
use http::Method;
use serde::{Deserialize, Serialize};

use crate::{models, types::*};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[must_use]
#[allow(clippy::large_enum_variant)]
pub enum MultipartRelatedRequestPostResponse {
/// OK
Status201_OK,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[must_use]
#[allow(clippy::large_enum_variant)]
pub enum MultipartRequestPostResponse {
/// OK
Status201_OK,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[must_use]
#[allow(clippy::large_enum_variant)]
pub enum MultipleIdenticalMimeTypesPostResponse {
/// OK
Status200_OK,
}

/// Default
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait Default {
/// MultipartRelatedRequestPost - POST /multipart_related_request
async fn multipart_related_request_post(
&self,
method: Method,
host: Host,
cookies: CookieJar,
body: axum::body::Body,
) -> Result<MultipartRelatedRequestPostResponse, String>;

/// MultipartRequestPost - POST /multipart_request
async fn multipart_request_post(
&self,
method: Method,
host: Host,
cookies: CookieJar,
body: Multipart,
) -> Result<MultipartRequestPostResponse, String>;

/// MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types
async fn multiple_identical_mime_types_post(
&self,
method: Method,
host: Host,
cookies: CookieJar,
body: axum::body::Body,
) -> Result<MultipleIdenticalMimeTypesPostResponse, String>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod default;

0 comments on commit e9f961e

Please sign in to comment.