diff --git a/bin/configs/rust-hyper-discriminator-reserved-keyword.yaml b/bin/configs/rust-hyper-discriminator-reserved-keyword.yaml new file mode 100644 index 000000000000..fb7cc3e75be0 --- /dev/null +++ b/bin/configs/rust-hyper-discriminator-reserved-keyword.yaml @@ -0,0 +1,8 @@ +generatorName: rust +outputDir: samples/client/others/rust/hyper/discriminator-reserved-keyword +library: hyper +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/discriminator-reserved-keyword.yaml +templateDir: modules/openapi-generator/src/main/resources/rust +additionalProperties: + supportAsync: false + packageName: discriminator-reserved-keyword-hyper diff --git a/bin/configs/rust-reqwest-discriminator-reserved-keyword.yaml b/bin/configs/rust-reqwest-discriminator-reserved-keyword.yaml new file mode 100644 index 000000000000..a35322cfe0e7 --- /dev/null +++ b/bin/configs/rust-reqwest-discriminator-reserved-keyword.yaml @@ -0,0 +1,8 @@ +generatorName: rust +outputDir: samples/client/others/rust/reqwest/discriminator-reserved-keyword +library: reqwest +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/discriminator-reserved-keyword.yaml +templateDir: modules/openapi-generator/src/main/resources/rust +additionalProperties: + supportAsync: false + packageName: discriminator-reserved-keyword-reqwest diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index d31bac3f77bb..98f7c18f7ba9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -318,6 +318,20 @@ public CodegenModel fromModel(String name, Schema model) { return mdl; } + @Override + public Map postProcessAllModels(Map objs) { + // Collect all models into a single list + List allModels = new ArrayList<>(); + for (ModelsMap models : objs.values()) { + allModels.addAll(models.getModels()); + } + + // Process oneOf discriminators across all models + postProcessOneOfModels(allModels); + + return super.postProcessAllModels(objs); + } + @Override public ModelsMap postProcessModels(ModelsMap objs) { for (ModelMap model : objs.getModels()) { @@ -666,6 +680,66 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } } + private void postProcessOneOfModels(List allModels) { + final HashMap> oneOfMapDiscriminator = new HashMap<>(); + + for (ModelMap mo : allModels) { + final CodegenModel cm = mo.getModel(); + + final CodegenComposedSchemas cs = cm.getComposedSchemas(); + + if (cs != null) { + final List csOneOf = cs.getOneOf(); + + if (csOneOf != null) { + for (CodegenProperty model : csOneOf) { + // Generate a valid name for the enum variant. + // Mainly needed for primitive types. + String[] modelParts = model.dataType.replace("<", "Of").replace(">", "").split("::"); + model.datatypeWithEnum = StringUtils.camelize(modelParts[modelParts.length - 1]); + + // Primitive type is not properly set, this overrides it to guarantee adequate model generation. + if (!model.getDataType().matches(String.format(Locale.ROOT, ".*::%s", model.getDatatypeWithEnum()))) { + model.isPrimitiveType = true; + } + } + + cs.setOneOf(csOneOf); + cm.setComposedSchemas(cs); + } + } + + if (cm.discriminator != null) { + for (String model : cm.oneOf) { + List discriminators = oneOfMapDiscriminator.getOrDefault(model, new ArrayList<>()); + discriminators.add(cm.discriminator.getPropertyBaseName()); + oneOfMapDiscriminator.put(model, discriminators); + } + } + } + + for (ModelMap mo : allModels) { + final CodegenModel cm = mo.getModel(); + + for (CodegenProperty var : cm.vars) { + var.isDiscriminator = false; + } + + final List discriminatorsForModel = oneOfMapDiscriminator.get(cm.getSchemaName()); + + if (discriminatorsForModel != null) { + for (String discriminator : discriminatorsForModel) { + for (CodegenProperty var : cm.vars) { + if (var.baseName.equals(discriminator)) { + var.isDiscriminator = true; + break; + } + } + } + } + } + } + @Override public void postProcessParameter(CodegenParameter parameter) { super.postProcessParameter(parameter); @@ -867,10 +941,10 @@ public String toDefaultValue(Schema p) { @Override protected ImmutableMap.Builder addMustacheLambdas() { return super.addMustacheLambdas() - // Convert variable names to lifetime names. - // Generally they are the same, but `#` is not valid in lifetime names. + // Convert raw identifiers to a safe name that can be used in other contexts + // like lifetimes or function names. // Rust uses `r#` prefix for variables that are also keywords. - .put("lifetimeName", new ReplaceAllLambda("^r#", "r_")); + .put("escapeRawIdentifier", new ReplaceAllLambda("^r#", "r_")); } public static Map> invertMap(Map map) { diff --git a/modules/openapi-generator/src/main/resources/rust/model.mustache b/modules/openapi-generator/src/main/resources/rust/model.mustache index a4970abf4299..2e452545d8c4 100644 --- a/modules/openapi-generator/src/main/resources/rust/model.mustache +++ b/modules/openapi-generator/src/main/resources/rust/model.mustache @@ -131,6 +131,11 @@ pub struct {{{classname}}} { {{#isByteArray}} {{#vendorExtensions.isMandatory}}#[serde_as(as = "serde_with::base64::Base64")]{{/vendorExtensions.isMandatory}}{{^vendorExtensions.isMandatory}}#[serde_as(as = "{{^serdeAsDoubleOption}}Option{{/serdeAsDoubleOption}}{{#serdeAsDoubleOption}}super::DoubleOption{{/serdeAsDoubleOption}}")]{{/vendorExtensions.isMandatory}} {{/isByteArray}} + {{#isDiscriminator}} + {{#required}} + #[serde(default = "{{{classname}}}::_default_for_{{#lambda.escapeRawIdentifier}}{{{name}}}{{/lambda.escapeRawIdentifier}}")] + {{/required}} + {{/isDiscriminator}} #[serde(rename = "{{{baseName}}}"{{^required}}{{#isNullable}}, default{{^isByteArray}}, with = "::serde_with::rust::double_option"{{/isByteArray}}{{/isNullable}}{{/required}}{{^required}}, skip_serializing_if = "Option::is_none"{{/required}}{{#required}}{{#isNullable}}, deserialize_with = "Option::deserialize"{{/isNullable}}{{/required}})] pub {{{name}}}: {{! ### Option Start @@ -172,6 +177,18 @@ impl {{{classname}}} { } } } +{{#vars}} +{{#isDiscriminator}} +{{#required}} + +impl {{{classname}}} { + fn _default_for_{{#lambda.escapeRawIdentifier}}{{{name}}}{{/lambda.escapeRawIdentifier}}() -> String { + String::from("{{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}{{classname}}{{/defaultValue}}") + } +} +{{/required}} +{{/isDiscriminator}} +{{/vars}} {{/oneOf.isEmpty}} {{^oneOf.isEmpty}} {{! TODO: add other vars that are not part of the oneOf}} diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest-trait/api.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest-trait/api.mustache index cf16c0fc24b2..86c0b8855bbe 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest-trait/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest-trait/api.mustache @@ -39,13 +39,13 @@ pub trait {{{classname}}}: Send + Sync { {{^vendorExtensions.x-group-parameters}} async fn {{{operationId}}}{{! ### Lifetimes - }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! + }}<{{#allParams}}'{{#lambda.escapeRawIdentifier}}{{{paramName}}}{{/lambda.escapeRawIdentifier}}{{^-last}}, {{/-last}}{{/allParams}}>{{! ### Function parameter names }}(&self, {{#allParams}}{{{paramName}}}: {{! ### Option Start }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! ### &str and Vec<&str> - }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! + }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.escapeRawIdentifier}}{{{paramName}}}{{/lambda.escapeRawIdentifier}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! ### UUIDs }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! ### Models and primative types @@ -147,13 +147,13 @@ impl {{classname}} for {{classname}}Client { {{^vendorExtensions.x-group-parameters}} async fn {{{operationId}}}{{! ### Lifetimes - }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! + }}<{{#allParams}}'{{#lambda.escapeRawIdentifier}}{{{paramName}}}{{/lambda.escapeRawIdentifier}}{{^-last}}, {{/-last}}{{/allParams}}>{{! ### Function parameter names }}(&self, {{#allParams}}{{{paramName}}}: {{! ### Option Start }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! ### &str and Vec<&str> - }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! + }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.escapeRawIdentifier}}{{{paramName}}}{{/lambda.escapeRawIdentifier}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! ### UUIDs }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! ### Models and primative types diff --git a/modules/openapi-generator/src/test/resources/3_0/oneOfDiscriminator.yaml b/modules/openapi-generator/src/test/resources/3_0/oneOfDiscriminator.yaml index 49bcc3ab60d3..4077c2043e82 100644 --- a/modules/openapi-generator/src/test/resources/3_0/oneOfDiscriminator.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/oneOfDiscriminator.yaml @@ -297,4 +297,4 @@ components: - $ref: '#/components/schemas/DiscOptionalTypeCorrect' - $ref: '#/components/schemas/FruitType' discriminator: - propertyName: fruitType + propertyName: fruitType \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/rust/discriminator-reserved-keyword.yaml b/modules/openapi-generator/src/test/resources/3_0/rust/discriminator-reserved-keyword.yaml new file mode 100644 index 000000000000..188c5ff17320 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/rust/discriminator-reserved-keyword.yaml @@ -0,0 +1,181 @@ +openapi: 3.0.1 +info: + title: Rust Discriminator Reserved Keyword Test + description: > + This tests discriminator fields with Rust reserved keywords to ensure + proper escaping and function name generation + version: 1.0.0 +servers: + - url: "http://localhost:8080" +paths: + /vehicle: + post: + summary: Create a vehicle + operationId: createVehicle + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Vehicle' + responses: + '201': + description: Vehicle created + content: + application/json: + schema: + $ref: '#/components/schemas/Vehicle' + /shape: + post: + summary: Create a shape + operationId: createShape + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Shape' + responses: + '201': + description: Shape created + content: + application/json: + schema: + $ref: '#/components/schemas/Shape' + +components: + schemas: + # Test case 1: Required discriminator with reserved keyword "type" + Vehicle: + type: object + oneOf: + - $ref: '#/components/schemas/Car' + - $ref: '#/components/schemas/Truck' + discriminator: + propertyName: type + mapping: + car: '#/components/schemas/Car' + truck: '#/components/schemas/Truck' + + Car: + type: object + required: + - type + - numDoors + properties: + type: + type: string + description: Vehicle type discriminator + default: Vehicle + numDoors: + type: integer + description: Number of doors + + Truck: + type: object + required: + - type + - cargoCapacity + properties: + type: + type: string + description: Vehicle type discriminator + cargoCapacity: + type: number + description: Cargo capacity in tons + + # Test case 2: Optional discriminator with reserved keyword "type" + Shape: + type: object + oneOf: + - $ref: '#/components/schemas/Circle' + - $ref: '#/components/schemas/Square' + discriminator: + propertyName: type + + Circle: + type: object + properties: + type: + type: string + description: Shape type discriminator + radius: + type: number + description: Circle radius + + Square: + type: object + properties: + type: + type: string + description: Shape type discriminator + size: + type: number + description: Square size + + # Test case 3: Discriminator with other reserved keywords + Message: + type: object + oneOf: + - $ref: '#/components/schemas/TextMessage' + - $ref: '#/components/schemas/ImageMessage' + discriminator: + propertyName: match + mapping: + text: '#/components/schemas/TextMessage' + image: '#/components/schemas/ImageMessage' + + TextMessage: + type: object + required: + - match + - content + properties: + match: + type: string + description: Message type discriminator (reserved keyword) + content: + type: string + description: Text content + + ImageMessage: + type: object + required: + - match + - url + properties: + match: + type: string + description: Message type discriminator (reserved keyword) + url: + type: string + description: Image URL + + # Test case 4: Reserved keyword in nested oneOf + Container: + type: object + oneOf: + - $ref: '#/components/schemas/BoxContainer' + - $ref: '#/components/schemas/BagContainer' + discriminator: + propertyName: return + + BoxContainer: + type: object + properties: + return: + type: string + description: Container type (reserved keyword) + dimensions: + type: string + description: Box dimensions + + BagContainer: + type: object + properties: + return: + type: string + description: Container type (reserved keyword) + material: + type: string + description: Bag material diff --git a/samples/client/others/rust/Cargo.lock b/samples/client/others/rust/Cargo.lock index 5c3649805991..21a222370199 100644 --- a/samples/client/others/rust/Cargo.lock +++ b/samples/client/others/rust/Cargo.lock @@ -166,6 +166,33 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "discriminator-reserved-keyword-hyper" +version = "1.0.0" +dependencies = [ + "base64 0.7.0", + "futures", + "http 0.2.11", + "http-body-util", + "hyper", + "hyper-util", + "serde", + "serde_json", + "serde_repr", + "url", +] + +[[package]] +name = "discriminator-reserved-keyword-reqwest" +version = "1.0.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "serde_repr", + "url", +] + [[package]] name = "empty-object-hyper" version = "1.0.0" diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/.gitignore b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.gitignore new file mode 100644 index 000000000000..6aa106405a4b --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator-ignore b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/FILES b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/FILES new file mode 100644 index 000000000000..63233cbd5473 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/FILES @@ -0,0 +1,37 @@ +.gitignore +.travis.yml +Cargo.toml +README.md +docs/BagContainer.md +docs/BoxContainer.md +docs/Car.md +docs/Circle.md +docs/Container.md +docs/DefaultApi.md +docs/ImageMessage.md +docs/Message.md +docs/Shape.md +docs/Square.md +docs/TextMessage.md +docs/Truck.md +docs/Vehicle.md +git_push.sh +src/apis/client.rs +src/apis/configuration.rs +src/apis/default_api.rs +src/apis/mod.rs +src/apis/request.rs +src/lib.rs +src/models/bag_container.rs +src/models/box_container.rs +src/models/car.rs +src/models/circle.rs +src/models/container.rs +src/models/image_message.rs +src/models/message.rs +src/models/mod.rs +src/models/shape.rs +src/models/square.rs +src/models/text_message.rs +src/models/truck.rs +src/models/vehicle.rs diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/VERSION b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/VERSION new file mode 100644 index 000000000000..2fb556b60635 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.18.0-SNAPSHOT diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/.travis.yml b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.travis.yml new file mode 100644 index 000000000000..22761ba7ee19 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/Cargo.toml b/samples/client/others/rust/hyper/discriminator-reserved-keyword/Cargo.toml new file mode 100644 index 000000000000..74b46168a403 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "discriminator-reserved-keyword-hyper" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation " +# Override this license by providing a License Object in the OpenAPI. +license = "Unlicense" +edition = "2021" + +[dependencies] +serde = { version = "^1.0", features = ["derive"] } +serde_json = "^1.0" +serde_repr = "^0.1" +url = "^2.5" +hyper = { version = "^1.3.1", features = ["full"] } +hyper-util = { version = "0.1.5", features = ["client", "client-legacy", "http1", "http2"] } +http-body-util = { version = "0.1.2" } +http = "~0.2" +base64 = "~0.7.0" +futures = "^0.3" diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/README.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/README.md new file mode 100644 index 000000000000..134c18055bff --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/README.md @@ -0,0 +1,59 @@ +# Rust API client for discriminator-reserved-keyword-hyper + +This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + + + +## 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 +- Generator version: 7.18.0-SNAPSHOT +- Build package: `org.openapitools.codegen.languages.RustClientCodegen` + +## Installation + +Put the package under your project folder in a directory named `discriminator-reserved-keyword-hyper` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +discriminator-reserved-keyword-hyper = { path = "./discriminator-reserved-keyword-hyper" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:8080* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**create_shape**](docs/DefaultApi.md#create_shape) | **Post** /shape | Create a shape +*DefaultApi* | [**create_vehicle**](docs/DefaultApi.md#create_vehicle) | **Post** /vehicle | Create a vehicle + + +## Documentation For Models + + - [BagContainer](docs/BagContainer.md) + - [BoxContainer](docs/BoxContainer.md) + - [Car](docs/Car.md) + - [Circle](docs/Circle.md) + - [Container](docs/Container.md) + - [ImageMessage](docs/ImageMessage.md) + - [Message](docs/Message.md) + - [Shape](docs/Shape.md) + - [Square](docs/Square.md) + - [TextMessage](docs/TextMessage.md) + - [Truck](docs/Truck.md) + - [Vehicle](docs/Vehicle.md) + + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BagContainer.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BagContainer.md new file mode 100644 index 000000000000..2bbb11f9abba --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BagContainer.md @@ -0,0 +1,12 @@ +# BagContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#return** | Option<**String**> | Container type (reserved keyword) | [optional] +**material** | Option<**String**> | Bag material | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BoxContainer.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BoxContainer.md new file mode 100644 index 000000000000..da1ce1b08385 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/BoxContainer.md @@ -0,0 +1,12 @@ +# BoxContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#return** | Option<**String**> | Container type (reserved keyword) | [optional] +**dimensions** | Option<**String**> | Box dimensions | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Car.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Car.md new file mode 100644 index 000000000000..de45d0d783b1 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Car.md @@ -0,0 +1,12 @@ +# Car + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | Vehicle type discriminator | [default to Vehicle] +**num_doors** | **i32** | Number of doors | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Circle.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Circle.md new file mode 100644 index 000000000000..0a732b117ba0 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Circle.md @@ -0,0 +1,12 @@ +# Circle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**radius** | Option<**f64**> | Circle radius | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Container.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Container.md new file mode 100644 index 000000000000..916bd71a8718 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Container.md @@ -0,0 +1,10 @@ +# Container + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/DefaultApi.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/DefaultApi.md new file mode 100644 index 000000000000..c3e92f70dab5 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/DefaultApi.md @@ -0,0 +1,66 @@ +# \DefaultApi + +All URIs are relative to *http://localhost:8080* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_shape**](DefaultApi.md#create_shape) | **Post** /shape | Create a shape +[**create_vehicle**](DefaultApi.md#create_vehicle) | **Post** /vehicle | Create a vehicle + + + +## create_shape + +> models::Shape create_shape(shape) +Create a shape + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**shape** | [**Shape**](Shape.md) | | [required] | + +### Return type + +[**models::Shape**](Shape.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## create_vehicle + +> models::Vehicle create_vehicle(vehicle) +Create a vehicle + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**vehicle** | [**Vehicle**](Vehicle.md) | | [required] | + +### Return type + +[**models::Vehicle**](Vehicle.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/ImageMessage.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/ImageMessage.md new file mode 100644 index 000000000000..d10d6ecfd956 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/ImageMessage.md @@ -0,0 +1,12 @@ +# ImageMessage + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | **String** | Message type discriminator (reserved keyword) | +**url** | **String** | Image URL | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Message.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Message.md new file mode 100644 index 000000000000..df76c4e6ef0a --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Message.md @@ -0,0 +1,10 @@ +# Message + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Rectangle.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Rectangle.md new file mode 100644 index 000000000000..a4d36e449410 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Rectangle.md @@ -0,0 +1,13 @@ +# Rectangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**width** | Option<**f64**> | Rectangle width | [optional] +**height** | Option<**f64**> | Rectangle height | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Shape.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Shape.md new file mode 100644 index 000000000000..87fa99a64217 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Shape.md @@ -0,0 +1,10 @@ +# Shape + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Square.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Square.md new file mode 100644 index 000000000000..35d8a5254a1c --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Square.md @@ -0,0 +1,12 @@ +# Square + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**size** | Option<**f64**> | Square size | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/TextMessage.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/TextMessage.md new file mode 100644 index 000000000000..6dad04adc098 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/TextMessage.md @@ -0,0 +1,12 @@ +# TextMessage + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | **String** | Message type discriminator (reserved keyword) | +**content** | **String** | Text content | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Truck.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Truck.md new file mode 100644 index 000000000000..1db4036eb0de --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Truck.md @@ -0,0 +1,12 @@ +# Truck + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | Vehicle type discriminator | +**cargo_capacity** | **f64** | Cargo capacity in tons | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Vehicle.md b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Vehicle.md new file mode 100644 index 000000000000..e2371926e7c3 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/docs/Vehicle.md @@ -0,0 +1,10 @@ +# Vehicle + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/git_push.sh b/samples/client/others/rust/hyper/discriminator-reserved-keyword/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/client.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/client.rs new file mode 100644 index 000000000000..5554552ee23e --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/client.rs @@ -0,0 +1,25 @@ +use std::sync::Arc; + +use hyper; +use hyper_util::client::legacy::connect::Connect; +use super::configuration::Configuration; + +pub struct APIClient { + default_api: Box, +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient + where C: Clone + std::marker::Send + Sync + 'static { + let rc = Arc::new(configuration); + + APIClient { + default_api: Box::new(crate::apis::DefaultApiClient::new(rc.clone())), + } + } + + pub fn default_api(&self) -> &dyn crate::apis::DefaultApi{ + self.default_api.as_ref() + } + +} diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/configuration.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/configuration.rs new file mode 100644 index 000000000000..f57113f330ca --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/configuration.rs @@ -0,0 +1,92 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use hyper; +use hyper_util::client::legacy::Client; +use hyper_util::client::legacy::connect::Connect; +use hyper_util::client::legacy::connect::HttpConnector; +use hyper_util::rt::TokioExecutor; + +pub struct Configuration + where C: Clone + std::marker::Send + Sync + 'static { + pub base_path: String, + pub user_agent: Option, + pub client: Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration { + /// Construct a default [`Configuration`](Self) with a hyper client using a default + /// [`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector). + /// + /// Use [`with_client`](Configuration::with_client) to construct a Configuration with a + /// custom hyper client. + /// + /// # Example + /// + /// ``` + /// # use discriminator_reserved_keyword_hyper::apis::configuration::Configuration; + /// let api_config = Configuration { + /// basic_auth: Some(("user".into(), None)), + /// ..Configuration::new() + /// }; + /// ``` + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Configuration + where C: Clone + std::marker::Send + Sync { + + /// Construct a new Configuration with a custom hyper client. + /// + /// # Example + /// + /// ``` + /// # use core::time::Duration; + /// # use discriminator_reserved_keyword_hyper::apis::configuration::Configuration; + /// use hyper_util::client::legacy::Client; + /// use hyper_util::rt::TokioExecutor; + /// + /// let client = Client::builder(TokioExecutor::new()) + /// .pool_idle_timeout(Duration::from_secs(30)) + /// .build_http(); + /// + /// let api_config = Configuration::with_client(client); + /// ``` + pub fn with_client(client: Client) -> Configuration { + Configuration { + base_path: "http://localhost:8080".to_owned(), + user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), + client, + basic_auth: None, + oauth_access_token: None, + api_key: None, + } + } +} + +impl Default for Configuration { + fn default() -> Self { + let client = Client::builder(TokioExecutor::new()).build_http(); + Configuration::with_client(client) + } +} diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/default_api.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/default_api.rs new file mode 100644 index 000000000000..234484a73330 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/default_api.rs @@ -0,0 +1,64 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use std::sync::Arc; +use std::borrow::Borrow; +use std::pin::Pin; +#[allow(unused_imports)] +use std::option::Option; + +use hyper; +use hyper_util::client::legacy::connect::Connect; +use futures::Future; + +use crate::models; +use super::{Error, configuration}; +use super::request as __internal_request; + +pub struct DefaultApiClient + where C: Clone + std::marker::Send + Sync + 'static { + configuration: Arc>, +} + +impl DefaultApiClient + where C: Clone + std::marker::Send + Sync { + pub fn new(configuration: Arc>) -> DefaultApiClient { + DefaultApiClient { + configuration, + } + } +} + +pub trait DefaultApi: Send + Sync { + fn create_shape(&self, shape: models::Shape) -> Pin> + Send>>; + fn create_vehicle(&self, vehicle: models::Vehicle) -> Pin> + Send>>; +} + +implDefaultApi for DefaultApiClient + where C: Clone + std::marker::Send + Sync { + #[allow(unused_mut)] + fn create_shape(&self, shape: models::Shape) -> Pin> + Send>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/shape".to_string()) + ; + req = req.with_body_param(shape); + + req.execute(self.configuration.borrow()) + } + + #[allow(unused_mut)] + fn create_vehicle(&self, vehicle: models::Vehicle) -> Pin> + Send>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/vehicle".to_string()) + ; + req = req.with_body_param(vehicle); + + req.execute(self.configuration.borrow()) + } + +} diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/mod.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/mod.rs new file mode 100644 index 000000000000..58227e44cb35 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/mod.rs @@ -0,0 +1,73 @@ +use std::fmt; +use std::fmt::Debug; + +use hyper; +use hyper::http; +use hyper_util::client::legacy::connect::Connect; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Api(ApiError), + Header(http::header::InvalidHeaderValue), + Http(http::Error), + Hyper(hyper::Error), + HyperClient(hyper_util::client::legacy::Error), + Serde(serde_json::Error), + UriError(http::uri::InvalidUri), +} + +pub struct ApiError { + pub code: hyper::StatusCode, + pub body: hyper::body::Incoming, +} + +impl Debug for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ApiError") + .field("code", &self.code) + .field("body", &"hyper::body::Incoming") + .finish() + } +} + +impl From<(hyper::StatusCode, hyper::body::Incoming)> for Error { + fn from(e: (hyper::StatusCode, hyper::body::Incoming)) -> Self { + Error::Api(ApiError { + code: e.0, + body: e.1, + }) + } +} + +impl From for Error { + fn from(e: http::Error) -> Self { + Error::Http(e) + } +} + +impl From for Error { + fn from(e: hyper_util::client::legacy::Error) -> Self { + Error::HyperClient(e) + } +} + +impl From for Error { + fn from(e: hyper::Error) -> Self { + Error::Hyper(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +mod request; + +mod default_api; +pub use self::default_api::{ DefaultApi, DefaultApiClient }; + +pub mod configuration; +pub mod client; diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/request.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/request.rs new file mode 100644 index 000000000000..a6f7b74cc6ef --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/apis/request.rs @@ -0,0 +1,247 @@ +use std::collections::HashMap; +use std::pin::Pin; + +use futures; +use futures::Future; +use futures::future::*; +use http_body_util::BodyExt; +use hyper; +use hyper_util::client::legacy::connect::Connect; +use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT}; +use serde; +use serde_json; + +use super::{configuration, Error}; + +pub(crate) struct ApiKey { + pub in_header: bool, + pub in_query: bool, + pub param_name: String, +} + +impl ApiKey { + fn key(&self, prefix: &Option, key: &str) -> String { + match prefix { + None => key.to_owned(), + Some(ref prefix) => format!("{} {}", prefix, key), + } + } +} + +#[allow(dead_code)] +pub(crate) enum Auth { + None, + ApiKey(ApiKey), + Basic, + Oauth, +} + +/// If the authorization type is unspecified then it will be automatically detected based +/// on the configuration. This functionality is useful when the OpenAPI definition does not +/// include an authorization scheme. +pub(crate) struct Request { + auth: Option, + method: hyper::Method, + path: String, + query_params: HashMap, + no_return_type: bool, + path_params: HashMap, + form_params: HashMap, + header_params: HashMap, + // TODO: multiple body params are possible technically, but not supported here. + serialized_body: Option, +} + +#[allow(dead_code)] +impl Request { + pub fn new(method: hyper::Method, path: String) -> Self { + Request { + auth: None, + method, + path, + query_params: HashMap::new(), + path_params: HashMap::new(), + form_params: HashMap::new(), + header_params: HashMap::new(), + serialized_body: None, + no_return_type: false, + } + } + + pub fn with_body_param(mut self, param: T) -> Self { + self.serialized_body = Some(serde_json::to_string(¶m).unwrap()); + self + } + + pub fn with_header_param(mut self, basename: String, param: String) -> Self { + self.header_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_query_param(mut self, basename: String, param: String) -> Self { + self.query_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_path_param(mut self, basename: String, param: String) -> Self { + self.path_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_form_param(mut self, basename: String, param: String) -> Self { + self.form_params.insert(basename, param); + self + } + + pub fn returns_nothing(mut self) -> Self { + self.no_return_type = true; + self + } + + pub fn with_auth(mut self, auth: Auth) -> Self { + self.auth = Some(auth); + self + } + + pub fn execute<'a, C, U>( + self, + conf: &configuration::Configuration, + ) -> Pin> + 'a + Send>> + where + C: Connect + Clone + std::marker::Send + Sync, + U: Sized + std::marker::Send + 'a, + for<'de> U: serde::Deserialize<'de>, + { + let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); + + let mut path = self.path; + for (k, v) in self.path_params { + // replace {id} with the value of the id path param + path = path.replace(&format!("{{{}}}", k), &v); + } + + for (key, val) in self.query_params { + query_string.append_pair(&key, &val); + } + + let mut uri_str = format!("{}{}", conf.base_path, path); + + let query_string_str = query_string.finish(); + if !query_string_str.is_empty() { + uri_str += "?"; + uri_str += &query_string_str; + } + let uri: hyper::Uri = match uri_str.parse() { + Err(e) => return Box::pin(futures::future::err(Error::UriError(e))), + Ok(u) => u, + }; + + let mut req_builder = hyper::Request::builder() + .uri(uri) + .method(self.method); + + // Detect the authorization type if it hasn't been set. + let auth = self.auth.unwrap_or_else(|| + if conf.api_key.is_some() { + panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition") + } else if conf.oauth_access_token.is_some() { + Auth::Oauth + } else if conf.basic_auth.is_some() { + Auth::Basic + } else { + Auth::None + } + ); + match auth { + Auth::ApiKey(apikey) => { + if let Some(ref key) = conf.api_key { + let val = apikey.key(&key.prefix, &key.key); + if apikey.in_query { + query_string.append_pair(&apikey.param_name, &val); + } + if apikey.in_header { + req_builder = req_builder.header(&apikey.param_name, val); + } + } + } + Auth::Basic => { + if let Some(ref auth_conf) = conf.basic_auth { + let mut text = auth_conf.0.clone(); + text.push(':'); + if let Some(ref pass) = auth_conf.1 { + text.push_str(&pass[..]); + } + let encoded = base64::encode(&text); + req_builder = req_builder.header(AUTHORIZATION, encoded); + } + } + Auth::Oauth => { + if let Some(ref token) = conf.oauth_access_token { + let text = "Bearer ".to_owned() + token; + req_builder = req_builder.header(AUTHORIZATION, text); + } + } + Auth::None => {} + } + + if let Some(ref user_agent) = conf.user_agent { + req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) { + Ok(header_value) => header_value, + Err(e) => return Box::pin(futures::future::err(super::Error::Header(e))) + }); + } + + for (k, v) in self.header_params { + req_builder = req_builder.header(&k, v); + } + + let req_headers = req_builder.headers_mut().unwrap(); + let request_result = if self.form_params.len() > 0 { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded")); + let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); + for (k, v) in self.form_params { + enc.append_pair(&k, &v); + } + req_builder.body(enc.finish()) + } else if let Some(body) = self.serialized_body { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + req_headers.insert(CONTENT_LENGTH, body.len().into()); + req_builder.body(body) + } else { + req_builder.body(String::new()) + }; + let request = match request_result { + Ok(request) => request, + Err(e) => return Box::pin(futures::future::err(Error::from(e))) + }; + + let no_return_type = self.no_return_type; + Box::pin(conf.client + .request(request) + .map_err(|e| Error::from(e)) + .and_then(move |response| { + let status = response.status(); + if !status.is_success() { + futures::future::err::(Error::from((status, response.into_body()))).boxed() + } else if no_return_type { + // This is a hack; if there's no_ret_type, U is (), but serde_json gives an + // error when deserializing "" into (), so deserialize 'null' into it + // instead. + // An alternate option would be to require U: Default, and then return + // U::default() here instead since () implements that, but then we'd + // need to impl default for all models. + futures::future::ok::(serde_json::from_str("null").expect("serde null value")).boxed() + } else { + let collect = response.into_body().collect().map_err(Error::from); + collect.map(|collected| { + collected.and_then(|collected| { + serde_json::from_slice(&collected.to_bytes()).map_err(Error::from) + }) + }).boxed() + } + })) + } +} diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/lib.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/lib.rs new file mode 100644 index 000000000000..f5cfd2315405 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/lib.rs @@ -0,0 +1,12 @@ +#![allow(unused_imports)] +#![allow(clippy::too_many_arguments)] + +extern crate serde_repr; +extern crate serde; +extern crate serde_json; +extern crate url; +extern crate hyper; +extern crate futures; + +pub mod apis; +pub mod models; diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/bag_container.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/bag_container.rs new file mode 100644 index 000000000000..82b133d67556 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/bag_container.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct BagContainer { + /// Container type (reserved keyword) + #[serde(rename = "return", skip_serializing_if = "Option::is_none")] + pub r#return: Option, + /// Bag material + #[serde(rename = "material", skip_serializing_if = "Option::is_none")] + pub material: Option, +} + +impl BagContainer { + pub fn new() -> BagContainer { + BagContainer { + r#return: None, + material: None, + } + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/box_container.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/box_container.rs new file mode 100644 index 000000000000..0c7b4e0b1b8e --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/box_container.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct BoxContainer { + /// Container type (reserved keyword) + #[serde(rename = "return", skip_serializing_if = "Option::is_none")] + pub r#return: Option, + /// Box dimensions + #[serde(rename = "dimensions", skip_serializing_if = "Option::is_none")] + pub dimensions: Option, +} + +impl BoxContainer { + pub fn new() -> BoxContainer { + BoxContainer { + r#return: None, + dimensions: None, + } + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/car.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/car.rs new file mode 100644 index 000000000000..584f07cb9de0 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/car.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Car { + /// Vehicle type discriminator + #[serde(default = "Car::_default_for_r_type")] + #[serde(rename = "type")] + pub r#type: String, + /// Number of doors + #[serde(rename = "numDoors")] + pub num_doors: i32, +} + +impl Car { + pub fn new(r#type: String, num_doors: i32) -> Car { + Car { + r#type, + num_doors, + } + } +} + +impl Car { + fn _default_for_r_type() -> String { + String::from("Vehicle") + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/circle.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/circle.rs new file mode 100644 index 000000000000..5f08f59240b2 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/circle.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Circle { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Circle radius + #[serde(rename = "radius", skip_serializing_if = "Option::is_none")] + pub radius: Option, +} + +impl Circle { + pub fn new() -> Circle { + Circle { + r#type: None, + radius: None, + } + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/container.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/container.rs new file mode 100644 index 000000000000..50ad421c96aa --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/container.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "return")] +pub enum Container { + #[serde(rename="BoxContainer")] + BoxContainer(Box), + #[serde(rename="BagContainer")] + BagContainer(Box), +} + +impl Default for Container { + fn default() -> Self { + Self::BoxContainer(Default::default()) + } +} + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/image_message.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/image_message.rs new file mode 100644 index 000000000000..3898740dc96d --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/image_message.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImageMessage { + /// Message type discriminator (reserved keyword) + #[serde(default = "ImageMessage::_default_for_r_match")] + #[serde(rename = "match")] + pub r#match: String, + /// Image URL + #[serde(rename = "url")] + pub url: String, +} + +impl ImageMessage { + pub fn new(r#match: String, url: String) -> ImageMessage { + ImageMessage { + r#match, + url, + } + } +} + +impl ImageMessage { + fn _default_for_r_match() -> String { + String::from("ImageMessage") + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/message.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/message.rs new file mode 100644 index 000000000000..b254632b81ce --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/message.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "match")] +pub enum Message { + #[serde(rename="text")] + Text(Box), + #[serde(rename="image")] + Image(Box), +} + +impl Default for Message { + fn default() -> Self { + Self::Text(Default::default()) + } +} + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/mod.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/mod.rs new file mode 100644 index 000000000000..3fb5a2431318 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/mod.rs @@ -0,0 +1,24 @@ +pub mod bag_container; +pub use self::bag_container::BagContainer; +pub mod box_container; +pub use self::box_container::BoxContainer; +pub mod car; +pub use self::car::Car; +pub mod circle; +pub use self::circle::Circle; +pub mod container; +pub use self::container::Container; +pub mod image_message; +pub use self::image_message::ImageMessage; +pub mod message; +pub use self::message::Message; +pub mod shape; +pub use self::shape::Shape; +pub mod square; +pub use self::square::Square; +pub mod text_message; +pub use self::text_message::TextMessage; +pub mod truck; +pub use self::truck::Truck; +pub mod vehicle; +pub use self::vehicle::Vehicle; diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/rectangle.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/rectangle.rs new file mode 100644 index 000000000000..637e60589be1 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/rectangle.rs @@ -0,0 +1,36 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rectangle { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Rectangle width + #[serde(rename = "width", skip_serializing_if = "Option::is_none")] + pub width: Option, + /// Rectangle height + #[serde(rename = "height", skip_serializing_if = "Option::is_none")] + pub height: Option, +} + +impl Rectangle { + pub fn new() -> Rectangle { + Rectangle { + r#type: None, + width: None, + height: None, + } + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/shape.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/shape.rs new file mode 100644 index 000000000000..d172e521ad33 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/shape.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Shape { + #[serde(rename="Circle")] + Circle(Box), + #[serde(rename="Square")] + Square(Box), +} + +impl Default for Shape { + fn default() -> Self { + Self::Circle(Default::default()) + } +} + + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/square.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/square.rs new file mode 100644 index 000000000000..dab9fda39fc4 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/square.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Square { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Square size + #[serde(rename = "size", skip_serializing_if = "Option::is_none")] + pub size: Option, +} + +impl Square { + pub fn new() -> Square { + Square { + r#type: None, + size: None, + } + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/text_message.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/text_message.rs new file mode 100644 index 000000000000..feb55907f47e --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/text_message.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextMessage { + /// Message type discriminator (reserved keyword) + #[serde(default = "TextMessage::_default_for_r_match")] + #[serde(rename = "match")] + pub r#match: String, + /// Text content + #[serde(rename = "content")] + pub content: String, +} + +impl TextMessage { + pub fn new(r#match: String, content: String) -> TextMessage { + TextMessage { + r#match, + content, + } + } +} + +impl TextMessage { + fn _default_for_r_match() -> String { + String::from("TextMessage") + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/truck.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/truck.rs new file mode 100644 index 000000000000..be106c59c350 --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/truck.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Truck { + /// Vehicle type discriminator + #[serde(default = "Truck::_default_for_r_type")] + #[serde(rename = "type")] + pub r#type: String, + /// Cargo capacity in tons + #[serde(rename = "cargoCapacity")] + pub cargo_capacity: f64, +} + +impl Truck { + pub fn new(r#type: String, cargo_capacity: f64) -> Truck { + Truck { + r#type, + cargo_capacity, + } + } +} + +impl Truck { + fn _default_for_r_type() -> String { + String::from("Truck") + } +} + diff --git a/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/vehicle.rs b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/vehicle.rs new file mode 100644 index 000000000000..093652a4c20a --- /dev/null +++ b/samples/client/others/rust/hyper/discriminator-reserved-keyword/src/models/vehicle.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Vehicle { + #[serde(rename="car")] + Car(Box), + #[serde(rename="truck")] + Truck(Box), +} + +impl Default for Vehicle { + fn default() -> Self { + Self::Car(Default::default()) + } +} + + diff --git a/samples/client/others/rust/hyper/oneOf/src/models/foo.rs b/samples/client/others/rust/hyper/oneOf/src/models/foo.rs index becc6957dd5d..a8a724577898 100644 --- a/samples/client/others/rust/hyper/oneOf/src/models/foo.rs +++ b/samples/client/others/rust/hyper/oneOf/src/models/foo.rs @@ -26,6 +26,7 @@ pub struct Foo { #[serde(rename = "@baseType", skip_serializing_if = "Option::is_none")] pub at_base_type: Option, /// When sub-classing, this defines the sub-class Extensible name + #[serde(default = "Foo::_default_for_at_type")] #[serde(rename = "@type")] pub at_type: String, #[serde(rename = "fooPropA", skip_serializing_if = "Option::is_none")] @@ -48,3 +49,9 @@ impl Foo { } } +impl Foo { + fn _default_for_at_type() -> String { + String::from("Foo") + } +} + diff --git a/samples/client/others/rust/hyper/oneOf/src/models/foo_ref.rs b/samples/client/others/rust/hyper/oneOf/src/models/foo_ref.rs index f4b3a2837fb7..4698f6666cab 100644 --- a/samples/client/others/rust/hyper/oneOf/src/models/foo_ref.rs +++ b/samples/client/others/rust/hyper/oneOf/src/models/foo_ref.rs @@ -26,6 +26,7 @@ pub struct FooRef { #[serde(rename = "@baseType", skip_serializing_if = "Option::is_none")] pub at_base_type: Option, /// When sub-classing, this defines the sub-class Extensible name + #[serde(default = "FooRef::_default_for_at_type")] #[serde(rename = "@type")] pub at_type: String, /// Name of the related entity. @@ -53,3 +54,9 @@ impl FooRef { } } +impl FooRef { + fn _default_for_at_type() -> String { + String::from("FooRef") + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.gitignore b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.gitignore new file mode 100644 index 000000000000..6aa106405a4b --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator-ignore b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/FILES b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/FILES new file mode 100644 index 000000000000..fb811465366f --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/FILES @@ -0,0 +1,35 @@ +.gitignore +.travis.yml +Cargo.toml +README.md +docs/BagContainer.md +docs/BoxContainer.md +docs/Car.md +docs/Circle.md +docs/Container.md +docs/DefaultApi.md +docs/ImageMessage.md +docs/Message.md +docs/Shape.md +docs/Square.md +docs/TextMessage.md +docs/Truck.md +docs/Vehicle.md +git_push.sh +src/apis/configuration.rs +src/apis/default_api.rs +src/apis/mod.rs +src/lib.rs +src/models/bag_container.rs +src/models/box_container.rs +src/models/car.rs +src/models/circle.rs +src/models/container.rs +src/models/image_message.rs +src/models/message.rs +src/models/mod.rs +src/models/shape.rs +src/models/square.rs +src/models/text_message.rs +src/models/truck.rs +src/models/vehicle.rs diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/VERSION b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/VERSION new file mode 100644 index 000000000000..2fb556b60635 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.18.0-SNAPSHOT diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.travis.yml b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.travis.yml new file mode 100644 index 000000000000..22761ba7ee19 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/Cargo.toml b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/Cargo.toml new file mode 100644 index 000000000000..b9d5fc56a0c2 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "discriminator-reserved-keyword-reqwest" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation " +# Override this license by providing a License Object in the OpenAPI. +license = "Unlicense" +edition = "2021" + +[dependencies] +serde = { version = "^1.0", features = ["derive"] } +serde_json = "^1.0" +serde_repr = "^0.1" +url = "^2.5" +reqwest = { version = "^0.12", default-features = false, features = ["json", "blocking", "multipart"] } + +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls-tls = ["reqwest/rustls-tls"] diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/README.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/README.md new file mode 100644 index 000000000000..ce619ddeeb59 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/README.md @@ -0,0 +1,59 @@ +# Rust API client for discriminator-reserved-keyword-reqwest + +This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + + + +## 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 +- Generator version: 7.18.0-SNAPSHOT +- Build package: `org.openapitools.codegen.languages.RustClientCodegen` + +## Installation + +Put the package under your project folder in a directory named `discriminator-reserved-keyword-reqwest` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +discriminator-reserved-keyword-reqwest = { path = "./discriminator-reserved-keyword-reqwest" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:8080* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**create_shape**](docs/DefaultApi.md#create_shape) | **POST** /shape | Create a shape +*DefaultApi* | [**create_vehicle**](docs/DefaultApi.md#create_vehicle) | **POST** /vehicle | Create a vehicle + + +## Documentation For Models + + - [BagContainer](docs/BagContainer.md) + - [BoxContainer](docs/BoxContainer.md) + - [Car](docs/Car.md) + - [Circle](docs/Circle.md) + - [Container](docs/Container.md) + - [ImageMessage](docs/ImageMessage.md) + - [Message](docs/Message.md) + - [Shape](docs/Shape.md) + - [Square](docs/Square.md) + - [TextMessage](docs/TextMessage.md) + - [Truck](docs/Truck.md) + - [Vehicle](docs/Vehicle.md) + + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BagContainer.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BagContainer.md new file mode 100644 index 000000000000..2bbb11f9abba --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BagContainer.md @@ -0,0 +1,12 @@ +# BagContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#return** | Option<**String**> | Container type (reserved keyword) | [optional] +**material** | Option<**String**> | Bag material | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BoxContainer.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BoxContainer.md new file mode 100644 index 000000000000..da1ce1b08385 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/BoxContainer.md @@ -0,0 +1,12 @@ +# BoxContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#return** | Option<**String**> | Container type (reserved keyword) | [optional] +**dimensions** | Option<**String**> | Box dimensions | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Car.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Car.md new file mode 100644 index 000000000000..de45d0d783b1 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Car.md @@ -0,0 +1,12 @@ +# Car + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | Vehicle type discriminator | [default to Vehicle] +**num_doors** | **i32** | Number of doors | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Circle.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Circle.md new file mode 100644 index 000000000000..0a732b117ba0 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Circle.md @@ -0,0 +1,12 @@ +# Circle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**radius** | Option<**f64**> | Circle radius | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Container.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Container.md new file mode 100644 index 000000000000..916bd71a8718 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Container.md @@ -0,0 +1,10 @@ +# Container + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/DefaultApi.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/DefaultApi.md new file mode 100644 index 000000000000..5c456ded10c1 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/DefaultApi.md @@ -0,0 +1,66 @@ +# \DefaultApi + +All URIs are relative to *http://localhost:8080* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_shape**](DefaultApi.md#create_shape) | **POST** /shape | Create a shape +[**create_vehicle**](DefaultApi.md#create_vehicle) | **POST** /vehicle | Create a vehicle + + + +## create_shape + +> models::Shape create_shape(shape) +Create a shape + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**shape** | [**Shape**](Shape.md) | | [required] | + +### Return type + +[**models::Shape**](Shape.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## create_vehicle + +> models::Vehicle create_vehicle(vehicle) +Create a vehicle + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**vehicle** | [**Vehicle**](Vehicle.md) | | [required] | + +### Return type + +[**models::Vehicle**](Vehicle.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/ImageMessage.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/ImageMessage.md new file mode 100644 index 000000000000..d10d6ecfd956 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/ImageMessage.md @@ -0,0 +1,12 @@ +# ImageMessage + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | **String** | Message type discriminator (reserved keyword) | +**url** | **String** | Image URL | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Message.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Message.md new file mode 100644 index 000000000000..df76c4e6ef0a --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Message.md @@ -0,0 +1,10 @@ +# Message + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Rectangle.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Rectangle.md new file mode 100644 index 000000000000..a4d36e449410 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Rectangle.md @@ -0,0 +1,13 @@ +# Rectangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**width** | Option<**f64**> | Rectangle width | [optional] +**height** | Option<**f64**> | Rectangle height | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Shape.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Shape.md new file mode 100644 index 000000000000..87fa99a64217 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Shape.md @@ -0,0 +1,10 @@ +# Shape + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Square.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Square.md new file mode 100644 index 000000000000..35d8a5254a1c --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Square.md @@ -0,0 +1,12 @@ +# Square + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | Option<**String**> | Shape type discriminator | [optional] +**size** | Option<**f64**> | Square size | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/TextMessage.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/TextMessage.md new file mode 100644 index 000000000000..6dad04adc098 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/TextMessage.md @@ -0,0 +1,12 @@ +# TextMessage + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | **String** | Message type discriminator (reserved keyword) | +**content** | **String** | Text content | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Truck.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Truck.md new file mode 100644 index 000000000000..1db4036eb0de --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Truck.md @@ -0,0 +1,12 @@ +# Truck + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | Vehicle type discriminator | +**cargo_capacity** | **f64** | Cargo capacity in tons | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Vehicle.md b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Vehicle.md new file mode 100644 index 000000000000..e2371926e7c3 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/docs/Vehicle.md @@ -0,0 +1,10 @@ +# Vehicle + +## Enum Variants + +| Name | Value | +|---- | -----| + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/git_push.sh b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/configuration.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/configuration.rs new file mode 100644 index 000000000000..1d3277bec55c --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/configuration.rs @@ -0,0 +1,51 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: reqwest::blocking::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, +} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "http://localhost:8080".to_owned(), + user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), + client: reqwest::blocking::Client::new(), + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + } + } +} diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/default_api.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/default_api.rs new file mode 100644 index 000000000000..94b469ce47ce --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/default_api.rs @@ -0,0 +1,106 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`create_shape`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateShapeError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`create_vehicle`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateVehicleError { + UnknownValue(serde_json::Value), +} + + +pub fn create_shape(configuration: &configuration::Configuration, shape: models::Shape) -> Result> { + // add a prefix to parameters to efficiently prevent name collisions + let p_body_shape = shape; + + let uri_str = format!("{}/shape", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + req_builder = req_builder.json(&p_body_shape); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req)?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text()?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Shape`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Shape`")))), + } + } else { + let content = resp.text()?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub fn create_vehicle(configuration: &configuration::Configuration, vehicle: models::Vehicle) -> Result> { + // add a prefix to parameters to efficiently prevent name collisions + let p_body_vehicle = vehicle; + + let uri_str = format!("{}/vehicle", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + req_builder = req_builder.json(&p_body_vehicle); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req)?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text()?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Vehicle`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Vehicle`")))), + } + } else { + let content = resp.text()?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/mod.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/mod.rs new file mode 100644 index 000000000000..fdcc89b36066 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/apis/mod.rs @@ -0,0 +1,116 @@ +use std::error; +use std::fmt; + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + }; + write!(f, "error in {}: {}", module, e) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => params.append(&mut parse_deep_object( + &format!("{}[{}]", prefix, key), + value, + )), + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{}[{}][{}]", prefix, key, i), + value, + )); + } + }, + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), + _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + } + + return params; + } + + unimplemented!("Only objects are supported with style=deepObject") +} + +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String) +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + +pub mod default_api; + +pub mod configuration; diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/lib.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/lib.rs new file mode 100644 index 000000000000..e1520628d762 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/lib.rs @@ -0,0 +1,11 @@ +#![allow(unused_imports)] +#![allow(clippy::too_many_arguments)] + +extern crate serde_repr; +extern crate serde; +extern crate serde_json; +extern crate url; +extern crate reqwest; + +pub mod apis; +pub mod models; diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/bag_container.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/bag_container.rs new file mode 100644 index 000000000000..82b133d67556 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/bag_container.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct BagContainer { + /// Container type (reserved keyword) + #[serde(rename = "return", skip_serializing_if = "Option::is_none")] + pub r#return: Option, + /// Bag material + #[serde(rename = "material", skip_serializing_if = "Option::is_none")] + pub material: Option, +} + +impl BagContainer { + pub fn new() -> BagContainer { + BagContainer { + r#return: None, + material: None, + } + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/box_container.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/box_container.rs new file mode 100644 index 000000000000..0c7b4e0b1b8e --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/box_container.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct BoxContainer { + /// Container type (reserved keyword) + #[serde(rename = "return", skip_serializing_if = "Option::is_none")] + pub r#return: Option, + /// Box dimensions + #[serde(rename = "dimensions", skip_serializing_if = "Option::is_none")] + pub dimensions: Option, +} + +impl BoxContainer { + pub fn new() -> BoxContainer { + BoxContainer { + r#return: None, + dimensions: None, + } + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/car.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/car.rs new file mode 100644 index 000000000000..584f07cb9de0 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/car.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Car { + /// Vehicle type discriminator + #[serde(default = "Car::_default_for_r_type")] + #[serde(rename = "type")] + pub r#type: String, + /// Number of doors + #[serde(rename = "numDoors")] + pub num_doors: i32, +} + +impl Car { + pub fn new(r#type: String, num_doors: i32) -> Car { + Car { + r#type, + num_doors, + } + } +} + +impl Car { + fn _default_for_r_type() -> String { + String::from("Vehicle") + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/circle.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/circle.rs new file mode 100644 index 000000000000..5f08f59240b2 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/circle.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Circle { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Circle radius + #[serde(rename = "radius", skip_serializing_if = "Option::is_none")] + pub radius: Option, +} + +impl Circle { + pub fn new() -> Circle { + Circle { + r#type: None, + radius: None, + } + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/container.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/container.rs new file mode 100644 index 000000000000..50ad421c96aa --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/container.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "return")] +pub enum Container { + #[serde(rename="BoxContainer")] + BoxContainer(Box), + #[serde(rename="BagContainer")] + BagContainer(Box), +} + +impl Default for Container { + fn default() -> Self { + Self::BoxContainer(Default::default()) + } +} + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/image_message.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/image_message.rs new file mode 100644 index 000000000000..3898740dc96d --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/image_message.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImageMessage { + /// Message type discriminator (reserved keyword) + #[serde(default = "ImageMessage::_default_for_r_match")] + #[serde(rename = "match")] + pub r#match: String, + /// Image URL + #[serde(rename = "url")] + pub url: String, +} + +impl ImageMessage { + pub fn new(r#match: String, url: String) -> ImageMessage { + ImageMessage { + r#match, + url, + } + } +} + +impl ImageMessage { + fn _default_for_r_match() -> String { + String::from("ImageMessage") + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/message.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/message.rs new file mode 100644 index 000000000000..b254632b81ce --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/message.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "match")] +pub enum Message { + #[serde(rename="text")] + Text(Box), + #[serde(rename="image")] + Image(Box), +} + +impl Default for Message { + fn default() -> Self { + Self::Text(Default::default()) + } +} + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/mod.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/mod.rs new file mode 100644 index 000000000000..3fb5a2431318 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/mod.rs @@ -0,0 +1,24 @@ +pub mod bag_container; +pub use self::bag_container::BagContainer; +pub mod box_container; +pub use self::box_container::BoxContainer; +pub mod car; +pub use self::car::Car; +pub mod circle; +pub use self::circle::Circle; +pub mod container; +pub use self::container::Container; +pub mod image_message; +pub use self::image_message::ImageMessage; +pub mod message; +pub use self::message::Message; +pub mod shape; +pub use self::shape::Shape; +pub mod square; +pub use self::square::Square; +pub mod text_message; +pub use self::text_message::TextMessage; +pub mod truck; +pub use self::truck::Truck; +pub mod vehicle; +pub use self::vehicle::Vehicle; diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/rectangle.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/rectangle.rs new file mode 100644 index 000000000000..637e60589be1 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/rectangle.rs @@ -0,0 +1,36 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rectangle { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Rectangle width + #[serde(rename = "width", skip_serializing_if = "Option::is_none")] + pub width: Option, + /// Rectangle height + #[serde(rename = "height", skip_serializing_if = "Option::is_none")] + pub height: Option, +} + +impl Rectangle { + pub fn new() -> Rectangle { + Rectangle { + r#type: None, + width: None, + height: None, + } + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/shape.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/shape.rs new file mode 100644 index 000000000000..d172e521ad33 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/shape.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Shape { + #[serde(rename="Circle")] + Circle(Box), + #[serde(rename="Square")] + Square(Box), +} + +impl Default for Shape { + fn default() -> Self { + Self::Circle(Default::default()) + } +} + + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/square.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/square.rs new file mode 100644 index 000000000000..dab9fda39fc4 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/square.rs @@ -0,0 +1,32 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Square { + /// Shape type discriminator + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub r#type: Option, + /// Square size + #[serde(rename = "size", skip_serializing_if = "Option::is_none")] + pub size: Option, +} + +impl Square { + pub fn new() -> Square { + Square { + r#type: None, + size: None, + } + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/text_message.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/text_message.rs new file mode 100644 index 000000000000..feb55907f47e --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/text_message.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextMessage { + /// Message type discriminator (reserved keyword) + #[serde(default = "TextMessage::_default_for_r_match")] + #[serde(rename = "match")] + pub r#match: String, + /// Text content + #[serde(rename = "content")] + pub content: String, +} + +impl TextMessage { + pub fn new(r#match: String, content: String) -> TextMessage { + TextMessage { + r#match, + content, + } + } +} + +impl TextMessage { + fn _default_for_r_match() -> String { + String::from("TextMessage") + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/truck.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/truck.rs new file mode 100644 index 000000000000..be106c59c350 --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/truck.rs @@ -0,0 +1,39 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Truck { + /// Vehicle type discriminator + #[serde(default = "Truck::_default_for_r_type")] + #[serde(rename = "type")] + pub r#type: String, + /// Cargo capacity in tons + #[serde(rename = "cargoCapacity")] + pub cargo_capacity: f64, +} + +impl Truck { + pub fn new(r#type: String, cargo_capacity: f64) -> Truck { + Truck { + r#type, + cargo_capacity, + } + } +} + +impl Truck { + fn _default_for_r_type() -> String { + String::from("Truck") + } +} + diff --git a/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/vehicle.rs b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/vehicle.rs new file mode 100644 index 000000000000..093652a4c20a --- /dev/null +++ b/samples/client/others/rust/reqwest/discriminator-reserved-keyword/src/models/vehicle.rs @@ -0,0 +1,29 @@ +/* + * Rust Discriminator Reserved Keyword Test + * + * This tests discriminator fields with Rust reserved keywords to ensure proper escaping and function name generation + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Vehicle { + #[serde(rename="car")] + Car(Box), + #[serde(rename="truck")] + Truck(Box), +} + +impl Default for Vehicle { + fn default() -> Self { + Self::Car(Default::default()) + } +} + + diff --git a/samples/client/others/rust/reqwest/oneOf/src/models/foo.rs b/samples/client/others/rust/reqwest/oneOf/src/models/foo.rs index becc6957dd5d..a8a724577898 100644 --- a/samples/client/others/rust/reqwest/oneOf/src/models/foo.rs +++ b/samples/client/others/rust/reqwest/oneOf/src/models/foo.rs @@ -26,6 +26,7 @@ pub struct Foo { #[serde(rename = "@baseType", skip_serializing_if = "Option::is_none")] pub at_base_type: Option, /// When sub-classing, this defines the sub-class Extensible name + #[serde(default = "Foo::_default_for_at_type")] #[serde(rename = "@type")] pub at_type: String, #[serde(rename = "fooPropA", skip_serializing_if = "Option::is_none")] @@ -48,3 +49,9 @@ impl Foo { } } +impl Foo { + fn _default_for_at_type() -> String { + String::from("Foo") + } +} + diff --git a/samples/client/others/rust/reqwest/oneOf/src/models/foo_ref.rs b/samples/client/others/rust/reqwest/oneOf/src/models/foo_ref.rs index f4b3a2837fb7..4698f6666cab 100644 --- a/samples/client/others/rust/reqwest/oneOf/src/models/foo_ref.rs +++ b/samples/client/others/rust/reqwest/oneOf/src/models/foo_ref.rs @@ -26,6 +26,7 @@ pub struct FooRef { #[serde(rename = "@baseType", skip_serializing_if = "Option::is_none")] pub at_base_type: Option, /// When sub-classing, this defines the sub-class Extensible name + #[serde(default = "FooRef::_default_for_at_type")] #[serde(rename = "@type")] pub at_type: String, /// Name of the related entity. @@ -53,3 +54,9 @@ impl FooRef { } } +impl FooRef { + fn _default_for_at_type() -> String { + String::from("FooRef") + } +} +