Skip to content

Add enum support to rust and skip none option serialization in clients #2244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,7 @@ public RustClientCodegen() {
// TODO(bcourtine): review file mapping.
// I tried to map as "std::io::File", but Reqwest multipart file requires a "AsRef<Path>" param.
// Getting a file from a Path is simple, but the opposite is difficult. So I map as "std::path::Path".
// Reference is required here because Path does not implement the "Sized" trait.
typeMapping.put("file", "&std::path::Path");
typeMapping.put("file", "std::path::PathBuf");
typeMapping.put("binary", "::models::File");
typeMapping.put("ByteArray", "String");
typeMapping.put("object", "Value");
Expand All @@ -150,6 +149,12 @@ public RustClientCodegen() {
setLibrary(HYPER_LIBRARY);
}

@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}

@Override
public void processOpts() {
super.processOpts();
Expand Down Expand Up @@ -487,25 +492,25 @@ public String toEnumDefaultValue(String value, String datatype) {
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "EMPTY";
return "Empty";
}

// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
varName = varName.replaceAll("-", "Minus");
varName = varName.replaceAll("\\+", "Plus");
varName = varName.replaceAll("\\.", "Dot");
return varName;
}

// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return getSymbolName(name).toUpperCase(Locale.ROOT);
return getSymbolName(name);
}

// string
String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT));
String enumName = sanitizeName(camelize(name));
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");

Expand All @@ -518,7 +523,9 @@ public String toEnumVarName(String name, String datatype) {

@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT);
// camelize the enum name
// phone_number => PhoneNumber
String enumName = camelize(toModelName(property.name));

// remove [] for array or map of enum
enumName = enumName.replace("[]", "");
Expand Down
65 changes: 4 additions & 61 deletions modules/openapi-generator/src/main/resources/rust/README.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})

## Installation

Put the package under your project folder and add the following in import:
Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`:

```
"./{{{packageName}}}"
openapi = { path = "./generated" }
```

## Documentation for API Endpoints
Expand All @@ -40,69 +40,12 @@ Class | Method | HTTP request | Description
{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}{{{classname}}}.md)
{{/model}}{{/models}}

## Documentation For Authorization

{{^authMethods}} Endpoints do not require authorization.
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}

## {{{name}}}

{{#isApiKey}}- **Type**: API key

Example
```
auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication

Example

```
auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "username",
Password: "password",
})
r, err := client.Service.Operation(auth, args)
```

{{/isBasic}}
{{#isOAuth}}

- **Type**: OAuth
- **Flow**: {{{flow}}}
- **Authorization URL**: {{{authorizationUrl}}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - **{{{scope}}}**: {{{description}}}
{{/scopes}}

Example

```
auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```

Or via OAuth2 module to automatically refresh tokens and perform user authentication.
To get access to the crate's generated documentation, use:

```
import "golang.org/x/oauth2"

/ .. Perform OAuth2 round trip request and obtain a token .. //

tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
cargo doc --open
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️ the docs updates!

```

{{/isOAuth}}
{{/authMethods}}

## Author

{{#apiInfo}}{{#apis}}{{^hasMore}}{{{infoEmail}}}
Expand Down
42 changes: 32 additions & 10 deletions modules/openapi-generator/src/main/resources/rust/model.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,28 @@
#[allow(unused_imports)]
use serde_json::Value;

{{!-- for enum schemas --}}
{{#isEnum}}
/// {{{description}}}
#[derive(Debug, Serialize, Deserialize)]
pub enum {{classname}} {
{{#allowableValues}}
{{#enumVars}}
#[serde(rename = "{{{value}}}")]
{{name}},
{{/enumVars}}{{/allowableValues}}
}
{{/isEnum}}

{{!-- for non-enum schemas --}}
{{^isEnum}}
#[derive(Debug, Serialize, Deserialize)]
pub struct {{{classname}}} {
{{#vars}}
{{#description}}
/// {{{description}}}
{{/description}}
#[serde(rename = "{{{baseName}}}")]
#[serde(rename = "{{{baseName}}}"{{^required}}, skip_serializing_if = "Option::is_none"{{/required}})]
pub {{{name}}}: {{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{^required}}Option<{{/required}}{{{dataType}}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^required}}>{{/required}},
{{/vars}}
}
Expand All @@ -31,16 +46,23 @@ impl {{{classname}}} {
}
}
}
{{/isEnum}}

{{!-- for properties that are of enum type --}}
{{#vars}}
{{#isEnum}}
// TODO enum
// List of {{{name}}}
//const (
// {{#allowableValues}}
// {{#enumVars}}
// {{{name}}} {{{classname}}} = "{{{value}}}"
// {{/enumVars}}
// {{/allowableValues}}
//)
/// {{{description}}}
#[derive(Debug, Serialize, Deserialize)]
pub enum {{enumName}} {
{{#allowableValues}}
{{#enumVars}}
#[serde(rename = "{{{value}}}")]
{{name}},
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}

{{/model}}
{{/models}}
43 changes: 7 additions & 36 deletions samples/client/petstore/rust-reqwest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.

## Overview

This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client.

- API version: 1.0.0
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.RustClientCodegen

## Installation
Put the package under your project folder and add the following in import:

Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`:

```
"./petstore_client"
openapi = { path = "./generated" }
```

## Documentation for API Endpoints
Expand Down Expand Up @@ -53,42 +56,10 @@ Class | Method | HTTP request | Description
- [User](docs/User.md)


## Documentation For Authorization
To get access to the crate's generated documentation, use:

## api_key
- **Type**: API key

Example
```
auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
## petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets

Example
```
auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```

Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```
import "golang.org/x/oauth2"

/ .. Perform OAuth2 round trip request and obtain a token .. //

tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
cargo doc --open
```

## Author
Expand Down
1 change: 1 addition & 0 deletions samples/client/petstore/rust-reqwest/docs/ApiResponse.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# ApiResponse

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **i32** | | [optional]
Expand Down
1 change: 1 addition & 0 deletions samples/client/petstore/rust-reqwest/docs/Category.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Category

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i64** | | [optional]
Expand Down
1 change: 1 addition & 0 deletions samples/client/petstore/rust-reqwest/docs/Order.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Order

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i64** | | [optional]
Expand Down
1 change: 1 addition & 0 deletions samples/client/petstore/rust-reqwest/docs/Pet.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Pet

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i64** | | [optional]
Expand Down
Loading