diff --git a/CI/bitrise.yml b/CI/bitrise.yml index f31294044f6..8a572ab864a 100644 --- a/CI/bitrise.yml +++ b/CI/bitrise.yml @@ -40,12 +40,21 @@ workflows: sh bin/swift4-all.sh - script@1.1.5: + title: Run Swift4 tests inputs: - content: | #!/usr/bin/env bash set -e - ./samples/client/petstore/swift4/swift4_test_all.sh && ./samples/client/test/swift4/swift4_test_all.sh && exit ${PIPESTATUS[0]} - title: Run Swift4 tests + ./samples/client/petstore/swift4/swift4_test_all.sh + ./samples/client/test/swift4/swift4_test_all.sh + - script@1.1.5: + title: Run all bin scripts + inputs: + - content: |- + #!/usr/bin/env bash + set -e + + ./bin/run-all-petstore diff --git a/README.md b/README.md index 6c42b513be1..5d2ef01e41d 100644 --- a/README.md +++ b/README.md @@ -482,7 +482,7 @@ SYNOPSIS [--model-name-prefix ] [--model-name-suffix ] [--model-package ] - [(-o | --output )] + [(-o | --output )] [(-p | --additional-properties )...] [--package-name ] [--release-note ] [--remove-operation-id-prefix] @@ -562,7 +562,7 @@ Here is a list of community-conitributed IDE plug-ins that integrate with OpenAP - Visual Studio: [REST API Client Code Generator](https://marketplace.visualstudio.com/items?itemName=ChristianResmaHelle.ApiClientCodeGenerator) by [Christian Resma Helle](https://christian-helle.blogspot.com/) - Visual Studio Code: [Codewind OpenAPI Tools](https://marketplace.visualstudio.com/items?itemName=IBM.codewind-openapi-tools) by [IBM](https://marketplace.visualstudio.com/publishers/IBM) - + ## [4 - Companies/Projects using OpenAPI Generator](#table-of-contents) Here are some companies/projects (alphabetical order) using OpenAPI Generator in production. To add your company/project to the list, please visit [README.md](README.md) and click on the icon to edit the page. @@ -609,6 +609,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Myworkout](https://myworkout.com) - [NamSor](https://www.namsor.com/) - [Openet](https://www.openet.com/) +- [Oracle](https://www.oracle.com/) - [Paxos](https://www.paxos.com) - [Ponicode](https://ponicode.dev/) - [Pricefx](https://www.pricefx.com/) @@ -728,7 +729,7 @@ OpenAPI Generator core team members are contributors who have been making signif * [@jmini](https://github.com/jmini) (2018/04) [:heart:](https://www.patreon.com/jmini) * [@etherealjoy](https://github.com/etherealjoy) (2019/06) -:heart: = Link to support the contributor directly +:heart: = Link to support the contributor directly #### Template Creator @@ -783,8 +784,9 @@ Here is a list of template creators: * Perl: @wing328 [:heart:](https://www.patreon.com/wing328) * PHP (Guzzle): @baartosz * PowerShell: @beatcracker + * Python-experimental: @spacether * R: @ramnov - * Ruby (Faraday): @meganemura @dkliban + * Ruby (Faraday): @meganemura @dkliban * Rust: @farcaller * Rust (rust-server): @metaswitch * Scala (scalaz & http4s): @tbrown1979 @@ -794,7 +796,7 @@ Here is a list of template creators: * Swift 4: @ehyche * TypeScript (Angular1): @mhardorf * TypeScript (Angular2): @roni-frantchi - * TypeScript (Angular6): @akehir + * TypeScript (Angular6): @akehir * TypeScript (Angular7): @topce * TypeScript (Axios): @nicokoenig * TypeScript (Fetch): @leonyu @@ -802,11 +804,11 @@ Here is a list of template creators: * TypeScript (Node): @mhardorf * TypeScript (Rxjs): @denyo * TypeScript (Inversify): @gualtierim - * TypeSCript (redux-query): @petejohansonxo + * TypeScript (redux-query): @petejohansonxo * Server Stubs * Ada: @stcarrez * C# ASP.NET 5: @jimschubert [:heart:](https://www.patreon.com/jimschubert) - * C# ASP.NET Core 3.0: @A-Joshi + * C# ASP.NET Core 3.0: @A-Joshi * C# NancyFX: @mstefaniuk * C++ (Qt5 QHttpEngine): @etherealjoy * C++ Pistache: @sebymiano @@ -849,7 +851,7 @@ Here is a list of template creators: * Configuration * Apache2: @stkrwork * Schema - * Avro: @sgadouar + * Avro: @sgadouar * GraphQL: @wing328 [:heart:](https://www.patreon.com/wing328) * MySQL: @ybelenko * Protocol Buffer: @wing328 @@ -892,11 +894,11 @@ If you want to join the committee, please kindly apply by sending an email to te | Android | @jaz-ah (2017/09) | | Apex | | | Bash | @frol (2017/07) @bkryza (2017/08) @kenjones-cisco (2017/09) | -| C | @zhemant (2018/11) | +| C | @zhemant (2018/11) @ityuhui (2019/12) | | C++ | @ravinikam (2017/07) @stkrwork (2017/07) @etherealjoy (2018/02) @martindelille (2018/03) @muttleyxd (2019/08) | | C# | @mandrean (2017/08), @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert) @frankyjuang (2019/09) | | Clojure | | -| Dart | @ircecho (2017/07) @swipesight (2018/09) @jaumard (2018/09) @nickmeinhold (2019/09) | +| Dart | @ircecho (2017/07) @swipesight (2018/09) @jaumard (2018/09) @nickmeinhold (2019/09) @athornz (2019/12) @amondnet (2019/12) | | Eiffel | @jvelilla (2017/09) | | Elixir | @mrmstn (2018/12) | | Elm | @eriktim (2018/09) | diff --git a/bin/ci/java-feign.json b/bin/ci/java-feign.json index 9bbda443d06..3e2d314e4d5 100644 --- a/bin/ci/java-feign.json +++ b/bin/ci/java-feign.json @@ -6,6 +6,7 @@ "templateDir": "modules/openapi-generator/src/main/resources/Java/libraries/feign", "additionalProperties": { "hideGenerationTimestamp": true, - "booleanGetterPrefix": "is" + "booleanGetterPrefix": "is", + "additionalModelTypeAnnotations": "@javax.annotation.concurrent.Immutable" } } \ No newline at end of file diff --git a/bin/ci/php-slim4-server-petstore.json b/bin/ci/php-slim4-server-petstore.json index 1bfab4a21bc..48de8dd691d 100644 --- a/bin/ci/php-slim4-server-petstore.json +++ b/bin/ci/php-slim4-server-petstore.json @@ -1,6 +1,6 @@ { "generatorName": "php-slim4", - "inputSpec": "modules/openapi-generator/src/test/resources/3_0/petstore.yaml", + "inputSpec": "modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", "outputDir": "samples/server/petstore/php-slim4", "templateDir": "modules/openapi-generator/src/main/resources/php-slim4-server" } \ No newline at end of file diff --git a/bin/kotlin-client-all.sh b/bin/kotlin-client-all.sh index f2ff479cb03..9fa9ee7de08 100755 --- a/bin/kotlin-client-all.sh +++ b/bin/kotlin-client-all.sh @@ -1,6 +1,7 @@ #!/bin/sh ./bin/kotlin-client-gson.sh +./bin/kotlin-client-moshi-codegen.sh ./bin/kotlin-client-nonpublic.sh ./bin/kotlin-client-okhttp3.sh ./bin/kotlin-client-petstore-multiplatform.sh @@ -8,3 +9,5 @@ ./bin/kotlin-client-string.sh ./bin/kotlin-client-threetenbp.sh ./bin/kotlin-client-nullable.sh +./bin/kotlin-client-retrofit2.sh +./bin/kotlin-client-json-request-date.sh diff --git a/bin/kotlin-client-json-request-date.sh b/bin/kotlin-client-json-request-date.sh new file mode 100755 index 00000000000..84ee2b74852 --- /dev/null +++ b/bin/kotlin-client-json-request-date.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore-with-date-field.yaml -g kotlin --artifact-id kotlin-petstore-json-request-date --additional-properties requestDateConverter=toJson -o samples/client/petstore/kotlin-json-request-date $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/kotlin-client-moshi-codegen.sh b/bin/kotlin-client-moshi-codegen.sh new file mode 100755 index 00000000000..c037b2efd88 --- /dev/null +++ b/bin/kotlin-client-moshi-codegen.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-moshi-codegen --additional-properties serializationLibrary=moshi,moshiCodeGen=true -o samples/client/petstore/kotlin-moshi-codegen $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/kotlin-client-retrofit2.sh b/bin/kotlin-client-retrofit2.sh new file mode 100755 index 00000000000..07bf41fa3e7 --- /dev/null +++ b/bin/kotlin-client-retrofit2.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-retrofit2 --library jvm-retrofit2 -o samples/client/petstore/kotlin-retrofit2 $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} \ No newline at end of file diff --git a/bin/kotlin-client-string.sh b/bin/kotlin-client-string.sh index 57fae03ab11..b5440137541 100755 --- a/bin/kotlin-client-string.sh +++ b/bin/kotlin-client-string.sh @@ -27,7 +27,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-string --additional-properties dateLibrary=string,serializableModel=true -o samples/client/petstore/kotlin-string $@" +ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-string --additional-properties dateLibrary=string,serializableModel=true,sortParamsByRequiredFlag=false,sortModelPropertiesByRequiredFlag=false -o samples/client/petstore/kotlin-string $@" java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/markdown-documentation-petstore.sh b/bin/markdown-documentation-petstore.sh new file mode 100755 index 00000000000..9031a3b7d51 --- /dev/null +++ b/bin/markdown-documentation-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/markdown-documentation -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g markdown -o samples/documentation/markdown $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/swift4-petstore-nonPublicApi.json b/bin/swift4-petstore-nonPublicApi.json index c8cf09f065e..f20305dec05 100644 --- a/bin/swift4-petstore-nonPublicApi.json +++ b/bin/swift4-petstore-nonPublicApi.json @@ -3,5 +3,6 @@ "podHomepage": "https://github.com/openapitools/openapi-generator", "podAuthors": "", "projectName": "PetstoreClient", - "nonPublicApi": true + "nonPublicApi": true, + "sortParamsByRequiredFlag": false } diff --git a/bin/windows/kotlin-client-all.bat b/bin/windows/kotlin-client-all.bat index 8a1b70a36e7..3833a95c7d1 100644 --- a/bin/windows/kotlin-client-all.bat +++ b/bin/windows/kotlin-client-all.bat @@ -1,8 +1,11 @@ call powershell -command "& '%~dp0\kotlin-client-gson.bat'" +call powershell -command "& '%~dp0\kotlin-client-moshi-codegen.bat'" call powershell -command "& '%~dp0\kotlin-client-nonpublic.bat'" call powershell -command "& '%~dp0\kotlin-client-okhttp3.bat'" call powershell -command "& '%~dp0\kotlin-client-petstore-multiplatform.bat'" call powershell -command "& '%~dp0\kotlin-client-petstore.bat'" call powershell -command "& '%~dp0\kotlin-client-string.bat'" call powershell -command "& '%~dp0\kotlin-client-threetenbp.bat'" -call powershell -command "& '%~dp0\kotlin-client-nullable.bat'" \ No newline at end of file +call powershell -command "& '%~dp0\kotlin-client-nullable.bat'" +call powershell -command "& '%~dp0\kotlin-client-json-request-date.bat'" +call powershell -command "& '%~dp0\kotlin-client-retrofit2.bat'" \ No newline at end of file diff --git a/bin/windows/kotlin-client-json-request-date.bat b/bin/windows/kotlin-client-json-request-date.bat new file mode 100644 index 00000000000..47fd16af7a0 --- /dev/null +++ b/bin/windows/kotlin-client-json-request-date.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "kotlin-petstore-json-request-date" -i modules\openapi-generator\src\test\resources\2_0\petstore-with-date-field.yaml -g kotlin --additional-properties requestDateConverter=toJson -o samples\client\petstore\kotlin-json-request-date + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/kotlin-client-moshi-codegen.bat b/bin/windows/kotlin-client-moshi-codegen.bat new file mode 100644 index 00000000000..5a2ff14ac75 --- /dev/null +++ b/bin/windows/kotlin-client-moshi-codegen.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "kotlin-petstore-moshi-codegen" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --additional-properties serializationLibrary=moshi,moshiCodeGen=true -o samples\client\petstore\kotlin-moshi-codegen + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/kotlin-client-retrofit2.bat b/bin/windows/kotlin-client-retrofit2.bat new file mode 100644 index 00000000000..123c8c28dc8 --- /dev/null +++ b/bin/windows/kotlin-client-retrofit2.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "kotlin-petstore-retrofit2" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g kotlin --library jvm-retrofit2 -o samples\client\petstore\kotlin-retrofit2 + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/markdown-documentation-petstore.bat b/bin/windows/markdown-documentation-petstore.bat new file mode 100644 index 00000000000..62c0744281a --- /dev/null +++ b/bin/windows/markdown-documentation-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "markdown-petstore-documentation" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g markdown -o samples\documentation\petstore\markdown + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/docs/generators.md b/docs/generators.md index ef2be7a5e98..59935cc3a64 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -128,6 +128,7 @@ The following generators are available: * [dynamic-html](generators/dynamic-html.md) * [html](generators/html.md) * [html2](generators/html2.md) +* [markdown (beta)](generators/markdown.md) * [openapi](generators/openapi.md) * [openapi-yaml](generators/openapi-yaml.md) diff --git a/docs/generators/ada-server.md b/docs/generators/ada-server.md index c775d88e23e..479a9a54bc6 100644 --- a/docs/generators/ada-server.md +++ b/docs/generators/ada-server.md @@ -6,6 +6,7 @@ sidebar_label: ada-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/ada.md b/docs/generators/ada.md index 6cd00504f8b..3341e163732 100644 --- a/docs/generators/ada.md +++ b/docs/generators/ada.md @@ -6,6 +6,7 @@ sidebar_label: ada | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/android.md b/docs/generators/android.md index a71797f303d..96c4695f43e 100644 --- a/docs/generators/android.md +++ b/docs/generators/android.md @@ -6,6 +6,7 @@ sidebar_label: android | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/apache2.md b/docs/generators/apache2.md index 2cefacb2966..bb7e852bfd9 100644 --- a/docs/generators/apache2.md +++ b/docs/generators/apache2.md @@ -6,6 +6,7 @@ sidebar_label: apache2 | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/apex.md b/docs/generators/apex.md index 82314835f38..bf9606d33af 100644 --- a/docs/generators/apex.md +++ b/docs/generators/apex.md @@ -6,6 +6,7 @@ sidebar_label: apex | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/asciidoc.md b/docs/generators/asciidoc.md index d006841c693..ed61ca4c77a 100644 --- a/docs/generators/asciidoc.md +++ b/docs/generators/asciidoc.md @@ -6,6 +6,7 @@ sidebar_label: asciidoc | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/avro-schema.md b/docs/generators/avro-schema.md index f8f924aaf84..97e3c9ec508 100644 --- a/docs/generators/avro-schema.md +++ b/docs/generators/avro-schema.md @@ -6,6 +6,7 @@ sidebar_label: avro-schema | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/bash.md b/docs/generators/bash.md index 35e442ddd83..d35e805585f 100644 --- a/docs/generators/bash.md +++ b/docs/generators/bash.md @@ -6,6 +6,7 @@ sidebar_label: bash | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/c.md b/docs/generators/c.md index f7be8e3b0b4..b60a7fbd492 100644 --- a/docs/generators/c.md +++ b/docs/generators/c.md @@ -6,6 +6,7 @@ sidebar_label: c | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/clojure.md b/docs/generators/clojure.md index 35386615734..2c49f189b2e 100644 --- a/docs/generators/clojure.md +++ b/docs/generators/clojure.md @@ -6,6 +6,7 @@ sidebar_label: clojure | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/cpp-qt5-client.md b/docs/generators/cpp-qt5-client.md index 4d98d7b3700..582f762740d 100644 --- a/docs/generators/cpp-qt5-client.md +++ b/docs/generators/cpp-qt5-client.md @@ -6,6 +6,7 @@ sidebar_label: cpp-qt5-client | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/cpp-qt5-qhttpengine-server.md b/docs/generators/cpp-qt5-qhttpengine-server.md index 19f7852a094..2531287fac3 100644 --- a/docs/generators/cpp-qt5-qhttpengine-server.md +++ b/docs/generators/cpp-qt5-qhttpengine-server.md @@ -6,6 +6,7 @@ sidebar_label: cpp-qt5-qhttpengine-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/cpp-tizen.md b/docs/generators/cpp-tizen.md index 5fd840afc63..babc5bd0148 100644 --- a/docs/generators/cpp-tizen.md +++ b/docs/generators/cpp-tizen.md @@ -6,6 +6,7 @@ sidebar_label: cpp-tizen | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/cwiki.md b/docs/generators/cwiki.md index 94f69357276..767d30b1b29 100644 --- a/docs/generators/cwiki.md +++ b/docs/generators/cwiki.md @@ -6,6 +6,7 @@ sidebar_label: cwiki | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index 0841a791b9d..adb9b30ad59 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -6,6 +6,7 @@ sidebar_label: dart-dio | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| @@ -17,3 +18,4 @@ sidebar_label: dart-dio |sourceFolder|Source folder for generated code| |null| |supportDart2|Support Dart 2.x (Dart 1.x support has been deprecated)| |true| |nullableFields|Is the null fields should be in the JSON payload| |null| +|dateLibrary|Option. Date library to use|
**core**
Dart core library (DateTime)
**timemachine**
Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.
|core| diff --git a/docs/generators/dart-jaguar.md b/docs/generators/dart-jaguar.md index 5aced175563..71eff87bf02 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -6,6 +6,7 @@ sidebar_label: dart-jaguar | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/dart.md b/docs/generators/dart.md index 07002e84938..365b2fc35a6 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -6,6 +6,7 @@ sidebar_label: dart | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/dynamic-html.md b/docs/generators/dynamic-html.md index 02869930abd..50752f564c3 100644 --- a/docs/generators/dynamic-html.md +++ b/docs/generators/dynamic-html.md @@ -6,6 +6,7 @@ sidebar_label: dynamic-html | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/elixir.md b/docs/generators/elixir.md index 276eb44397b..2fb1cf776b9 100644 --- a/docs/generators/elixir.md +++ b/docs/generators/elixir.md @@ -6,6 +6,7 @@ sidebar_label: elixir | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/fsharp-functions.md b/docs/generators/fsharp-functions.md index be33609bb51..145573d67d9 100644 --- a/docs/generators/fsharp-functions.md +++ b/docs/generators/fsharp-functions.md @@ -6,6 +6,7 @@ sidebar_label: fsharp-functions | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index 688b2b1ac93..a3a5463a3b0 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -6,6 +6,7 @@ sidebar_label: groovy | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/haskell-http-client.md b/docs/generators/haskell-http-client.md index 8f5285cb245..f79606c6db2 100644 --- a/docs/generators/haskell-http-client.md +++ b/docs/generators/haskell-http-client.md @@ -6,6 +6,7 @@ sidebar_label: haskell-http-client | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/haskell.md b/docs/generators/haskell.md index b828257f3f8..89cd90586df 100644 --- a/docs/generators/haskell.md +++ b/docs/generators/haskell.md @@ -6,6 +6,7 @@ sidebar_label: haskell | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/html.md b/docs/generators/html.md index a85ea85aef5..0c75b44dd0d 100644 --- a/docs/generators/html.md +++ b/docs/generators/html.md @@ -6,6 +6,7 @@ sidebar_label: html | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/html2.md b/docs/generators/html2.md index d1726b72a54..3b7775d5fcb 100644 --- a/docs/generators/html2.md +++ b/docs/generators/html2.md @@ -6,6 +6,7 @@ sidebar_label: html2 | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index 37856678e67..f50718a448d 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -6,6 +6,7 @@ sidebar_label: java-inflector | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index ece46f99046..d6f8235503f 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -6,6 +6,7 @@ sidebar_label: java-msf4j | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index 30eff4add44..a9ef34390f6 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -6,6 +6,7 @@ sidebar_label: java-pkmst | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index bad8968d3e2..bb4fb690a2e 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -6,6 +6,7 @@ sidebar_label: java-play-framework | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index 6b780fa3f41..dd4bac2ca0e 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -6,6 +6,7 @@ sidebar_label: java-undertow-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index 23aee105dd9..2cc47cad074 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -6,6 +6,7 @@ sidebar_label: java-vertx-web | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index 27240770c34..1ad75271039 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -6,6 +6,7 @@ sidebar_label: java-vertx | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/java.md b/docs/generators/java.md index 4cd473853b2..9c267d17fbf 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -6,6 +6,7 @@ sidebar_label: java | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/javascript-closure-angular.md b/docs/generators/javascript-closure-angular.md index d736d131cf3..20c4048feca 100644 --- a/docs/generators/javascript-closure-angular.md +++ b/docs/generators/javascript-closure-angular.md @@ -6,6 +6,7 @@ sidebar_label: javascript-closure-angular | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/javascript-flowtyped.md b/docs/generators/javascript-flowtyped.md index 946c1d086ca..f5fb5207f4e 100644 --- a/docs/generators/javascript-flowtyped.md +++ b/docs/generators/javascript-flowtyped.md @@ -6,6 +6,7 @@ sidebar_label: javascript-flowtyped | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/javascript.md b/docs/generators/javascript.md index 3fcf9cc6c09..23aa54a57be 100644 --- a/docs/generators/javascript.md +++ b/docs/generators/javascript.md @@ -6,6 +6,7 @@ sidebar_label: javascript | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index 5a1cbe843b4..ff8be783614 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-cxf-cdi | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index 46f554eb3d8..401b13a22c5 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-cxf-client | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index 9259685cc18..03dcf52b076 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-cxf-extended | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index bcb14352a97..5bb65f09b1e 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-cxf | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index ee1782b7337..489987ffc00 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-jersey | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index baa90886e53..3dce1089aed 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-resteasy-eap | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index 62e6fc5254e..4712a95cdc0 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-resteasy | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index 1051b458ecd..eac2f0d61b7 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -6,6 +6,7 @@ sidebar_label: jaxrs-spec | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/jmeter.md b/docs/generators/jmeter.md index 9872d3b347b..20f31834208 100644 --- a/docs/generators/jmeter.md +++ b/docs/generators/jmeter.md @@ -6,6 +6,7 @@ sidebar_label: jmeter | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index d84d2857173..135c5706697 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -15,6 +15,8 @@ sidebar_label: kotlin-server |serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson'| |moshi| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |modelMutable|Create mutable models| |false| |library|library template (sub-template)|
**ktor**
ktor framework
|ktor| |featureAutoHead|Automatically provide responses to HEAD requests for existing routes that have the GET verb defined.| |true| diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 5d67f4b8ec4..2ad78b7b90f 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -15,6 +15,8 @@ sidebar_label: kotlin-spring |serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson'| |moshi| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |modelMutable|Create mutable models| |false| |title|server title name or client service name| |OpenAPI Kotlin Spring| |basePackage|base package (invokerPackage) for generated code| |org.openapitools| diff --git a/docs/generators/kotlin-vertx.md b/docs/generators/kotlin-vertx.md index 496f1a7ef0d..fd37a2cc8db 100644 --- a/docs/generators/kotlin-vertx.md +++ b/docs/generators/kotlin-vertx.md @@ -15,4 +15,6 @@ sidebar_label: kotlin-vertx |serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson'| |moshi| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |modelMutable|Create mutable models| |false| diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index d64fd3964ff..f5771c07492 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -15,7 +15,10 @@ sidebar_label: kotlin |serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson'| |moshi| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |modelMutable|Create mutable models| |false| |dateLibrary|Option. Date library to use|
**string**
String
**java8**
Java 8 native JSR310 (jvm only)
**threetenbp**
Threetenbp (jvm only)
|java8| |collectionType|Option. Collection type to use|
**array**
kotlin.Array
**list**
kotlin.collections.List
|array| -|library|Library template (sub-template) to use|
**jvm-okhttp4**
[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
**jvm-okhttp3**
Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
**multiplatform**
Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.
|jvm-okhttp4| +|library|Library template (sub-template) to use|
**jvm-okhttp4**
[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
**jvm-okhttp3**
Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
**jvm-retrofit2**
Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
**multiplatform**
Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.
|jvm-okhttp4| +|requestDateConverter|JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)|
**toJson**
Date formater option using a json converter.
**toString**
[DEFAULT] Use the 'toString'-method of the date-time object to retrieve the related string representation.
|toString| diff --git a/docs/generators/markdown.md b/docs/generators/markdown.md new file mode 100644 index 00000000000..5fe5f9d699d --- /dev/null +++ b/docs/generators/markdown.md @@ -0,0 +1,12 @@ +--- +title: Config Options for markdown +sidebar_label: markdown +--- + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/nim.md b/docs/generators/nim.md index b7bdcee5d80..7368aa1e8b1 100644 --- a/docs/generators/nim.md +++ b/docs/generators/nim.md @@ -6,6 +6,7 @@ sidebar_label: nim | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/nodejs-express-server.md b/docs/generators/nodejs-express-server.md index bbe2659c213..0f003586445 100644 --- a/docs/generators/nodejs-express-server.md +++ b/docs/generators/nodejs-express-server.md @@ -6,6 +6,7 @@ sidebar_label: nodejs-express-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/nodejs-server-deprecated.md b/docs/generators/nodejs-server-deprecated.md index 13c9424641f..113637d89a0 100644 --- a/docs/generators/nodejs-server-deprecated.md +++ b/docs/generators/nodejs-server-deprecated.md @@ -6,6 +6,7 @@ sidebar_label: nodejs-server-deprecated | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/ocaml.md b/docs/generators/ocaml.md index e95ed3c59f2..2e9278e513e 100644 --- a/docs/generators/ocaml.md +++ b/docs/generators/ocaml.md @@ -6,6 +6,7 @@ sidebar_label: ocaml | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/openapi-yaml.md b/docs/generators/openapi-yaml.md index 5c551d77352..6c31814c58b 100644 --- a/docs/generators/openapi-yaml.md +++ b/docs/generators/openapi-yaml.md @@ -6,6 +6,7 @@ sidebar_label: openapi-yaml | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/openapi.md b/docs/generators/openapi.md index c0181ddce0d..b4fe2219132 100644 --- a/docs/generators/openapi.md +++ b/docs/generators/openapi.md @@ -6,6 +6,7 @@ sidebar_label: openapi | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md index 580869441aa..dee3787142d 100644 --- a/docs/generators/php-laravel.md +++ b/docs/generators/php-laravel.md @@ -6,6 +6,7 @@ sidebar_label: php-laravel | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md index 286804540aa..96af22e02a8 100644 --- a/docs/generators/php-lumen.md +++ b/docs/generators/php-lumen.md @@ -6,6 +6,7 @@ sidebar_label: php-lumen | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-silex.md b/docs/generators/php-silex.md index 61241269f85..67000a6a3b9 100644 --- a/docs/generators/php-silex.md +++ b/docs/generators/php-silex.md @@ -6,6 +6,7 @@ sidebar_label: php-silex | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md index 47784d3e934..b15405df2b5 100644 --- a/docs/generators/php-slim-deprecated.md +++ b/docs/generators/php-slim-deprecated.md @@ -6,6 +6,7 @@ sidebar_label: php-slim-deprecated | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md index 05307722bbb..6ca37b8adc5 100644 --- a/docs/generators/php-slim4.md +++ b/docs/generators/php-slim4.md @@ -6,6 +6,7 @@ sidebar_label: php-slim4 | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-symfony.md b/docs/generators/php-symfony.md index 04693e48d6f..913c5be6a53 100644 --- a/docs/generators/php-symfony.md +++ b/docs/generators/php-symfony.md @@ -6,6 +6,7 @@ sidebar_label: php-symfony | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-ze-ph.md b/docs/generators/php-ze-ph.md index 0eab64888b3..a1066f34dcd 100644 --- a/docs/generators/php-ze-ph.md +++ b/docs/generators/php-ze-ph.md @@ -6,6 +6,7 @@ sidebar_label: php-ze-ph | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php.md b/docs/generators/php.md index 24c3028d139..c7d1766f249 100644 --- a/docs/generators/php.md +++ b/docs/generators/php.md @@ -6,6 +6,7 @@ sidebar_label: php | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index 0a9ad07aee8..16a4fc8056f 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -6,6 +6,7 @@ sidebar_label: python-aiohttp | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index ae30ec6f0c6..21891902860 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -6,6 +6,7 @@ sidebar_label: python-blueplanet | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index f01e68d7213..05f6e46a1c6 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -6,6 +6,7 @@ sidebar_label: python-flask | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/ruby.md b/docs/generators/ruby.md index 54e03f1b804..17eab9c0299 100644 --- a/docs/generators/ruby.md +++ b/docs/generators/ruby.md @@ -6,6 +6,7 @@ sidebar_label: ruby | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-akka.md b/docs/generators/scala-akka.md index ed8b8c74843..ceae6b73ea1 100644 --- a/docs/generators/scala-akka.md +++ b/docs/generators/scala-akka.md @@ -6,6 +6,7 @@ sidebar_label: scala-akka | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-gatling.md b/docs/generators/scala-gatling.md index d4247564fbc..8f56ccebbf1 100644 --- a/docs/generators/scala-gatling.md +++ b/docs/generators/scala-gatling.md @@ -6,6 +6,7 @@ sidebar_label: scala-gatling | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-httpclient-deprecated.md b/docs/generators/scala-httpclient-deprecated.md index bd273634674..d27b8bf3a01 100644 --- a/docs/generators/scala-httpclient-deprecated.md +++ b/docs/generators/scala-httpclient-deprecated.md @@ -6,6 +6,7 @@ sidebar_label: scala-httpclient-deprecated | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-lagom-server.md b/docs/generators/scala-lagom-server.md index 36fb95eac67..c0d040c6425 100644 --- a/docs/generators/scala-lagom-server.md +++ b/docs/generators/scala-lagom-server.md @@ -6,6 +6,7 @@ sidebar_label: scala-lagom-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-play-server.md b/docs/generators/scala-play-server.md index 81ade4afdd4..1582e3959f6 100644 --- a/docs/generators/scala-play-server.md +++ b/docs/generators/scala-play-server.md @@ -6,6 +6,7 @@ sidebar_label: scala-play-server | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scalatra.md b/docs/generators/scalatra.md index dba381ee6fa..c55dc21c749 100644 --- a/docs/generators/scalatra.md +++ b/docs/generators/scalatra.md @@ -6,6 +6,7 @@ sidebar_label: scalatra | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scalaz.md b/docs/generators/scalaz.md index 787c221928a..bf097e1ced9 100644 --- a/docs/generators/scalaz.md +++ b/docs/generators/scalaz.md @@ -6,6 +6,7 @@ sidebar_label: scalaz | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/spring.md b/docs/generators/spring.md index 793dfbbaa69..6d6d462d800 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -6,6 +6,7 @@ sidebar_label: spring | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/swift2-deprecated.md b/docs/generators/swift2-deprecated.md index 4fa404bfc2c..1ba09b421c1 100644 --- a/docs/generators/swift2-deprecated.md +++ b/docs/generators/swift2-deprecated.md @@ -6,6 +6,7 @@ sidebar_label: swift2-deprecated | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/swift3-deprecated.md b/docs/generators/swift3-deprecated.md index 73eff0f12f6..d72fe8b9d25 100644 --- a/docs/generators/swift3-deprecated.md +++ b/docs/generators/swift3-deprecated.md @@ -6,6 +6,7 @@ sidebar_label: swift3-deprecated | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/swift4.md b/docs/generators/swift4.md index 5abbc3658cf..53f718d49cb 100644 --- a/docs/generators/swift4.md +++ b/docs/generators/swift4.md @@ -6,12 +6,14 @@ sidebar_label: swift4 | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |projectName|Project name in Xcode| |null| |responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result are available.| |null| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| |unwrapRequired|Treat 'required' properties in response as non-optional (which would crash the app if api returns null as opposed to required option specified in json schema| |null| |objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null| |podSource|Source information used for Podspec| |null| diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index 9c49c147614..11711420ff7 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -6,6 +6,7 @@ sidebar_label: typescript-angular | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-angularjs.md b/docs/generators/typescript-angularjs.md index ea20c438bf2..5fd86f3d8e1 100644 --- a/docs/generators/typescript-angularjs.md +++ b/docs/generators/typescript-angularjs.md @@ -6,6 +6,7 @@ sidebar_label: typescript-angularjs | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-aurelia.md b/docs/generators/typescript-aurelia.md index 74d84d9a0d7..fe5f6d13c96 100644 --- a/docs/generators/typescript-aurelia.md +++ b/docs/generators/typescript-aurelia.md @@ -6,6 +6,7 @@ sidebar_label: typescript-aurelia | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index db4f9b84b35..9b03c130acd 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -6,6 +6,7 @@ sidebar_label: typescript-axios | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index 6f806f268a6..d603f8de2db 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -6,6 +6,7 @@ sidebar_label: typescript-fetch | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-inversify.md b/docs/generators/typescript-inversify.md index 1209dbde068..3acc05d8b7e 100644 --- a/docs/generators/typescript-inversify.md +++ b/docs/generators/typescript-inversify.md @@ -6,6 +6,7 @@ sidebar_label: typescript-inversify | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-jquery.md b/docs/generators/typescript-jquery.md index b3ca91bcefd..da4df1c90a1 100644 --- a/docs/generators/typescript-jquery.md +++ b/docs/generators/typescript-jquery.md @@ -6,6 +6,7 @@ sidebar_label: typescript-jquery | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-node.md b/docs/generators/typescript-node.md index 2d3358b566c..aea7c2a40c5 100644 --- a/docs/generators/typescript-node.md +++ b/docs/generators/typescript-node.md @@ -6,6 +6,7 @@ sidebar_label: typescript-node | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-redux-query.md b/docs/generators/typescript-redux-query.md index b0e4b1bb122..1f4c0850ba2 100644 --- a/docs/generators/typescript-redux-query.md +++ b/docs/generators/typescript-redux-query.md @@ -6,6 +6,7 @@ sidebar_label: typescript-redux-query | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-rxjs.md b/docs/generators/typescript-rxjs.md index e2b08652946..a2473ca26f0 100644 --- a/docs/generators/typescript-rxjs.md +++ b/docs/generators/typescript-rxjs.md @@ -6,6 +6,7 @@ sidebar_label: typescript-rxjs | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/new-generator.md b/docs/new-generator.md index 8265e3fe0b8..dc83018900c 100644 --- a/docs/new-generator.md +++ b/docs/new-generator.md @@ -75,38 +75,39 @@ Examples: This script allows us to define a client, server, schema, or documentation generator. We'll focus on the simplest generator (documentation). The other generator types may require heavy extension of the "Config" base class, and these docs could very quickly become outdated. When creating a new generator, please review existing generators as a guideline for implementation. -Create a new Markdown generator: +Create a new Markdown generator, specifying CommonMark as the name to avoid conflicting with the built-in Markdown generator. ```bash -./new.sh -n markdown -d +./new.sh -n common-mark -d ``` You should see output similar to the following: ```bash -Creating modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java -Creating modules/openapi-generator/src/main/resources/markdown-documentation/README.mustache -Creating modules/openapi-generator/src/main/resources/markdown-documentation/model.mustache -Creating modules/openapi-generator/src/main/resources/markdown-documentation/api.mustache -Creating bin/windows/markdown-documentation-petstore.bat -Creating bin/markdown-documentation-petstore.sh +Creating modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CommonMarkDocumentationCodegen.java +Creating modules/openapi-generator/src/main/resources/common-mark-documentation/README.mustache +Creating modules/openapi-generator/src/main/resources/common-mark-documentation/model.mustache +Creating modules/openapi-generator/src/main/resources/common-mark-documentation/api.mustache +Creating bin/windows/common-mark-documentation-petstore.bat +Creating bin/common-mark-documentation-petstore.sh Finished. ``` ### Review Generated Config -Beginning with the "Codegen" file (`MarkdownDocumentationCodegen.java`), the constructor was created: +Beginning with the "Codegen" file (`CommonMarkDocumentationCodegen.java`), the constructor was created: ```java - public MarkdownDocumentationCodegen() { + public CommonMarkDocumentationCodegen() { super(); - outputFolder = "generated-code" + File.separator + "markdown"; + outputFolder = "generated-code" + File.separator + "common-mark"; modelTemplateFiles.put("model.mustache", ".zz"); apiTemplateFiles.put("api.mustache", ".zz"); - embeddedTemplateDir = templateDir = "markdown-documentation"; + embeddedTemplateDir = templateDir = "common-mark-documentation"; apiPackage = File.separator + "Apis"; modelPackage = File.separator + "Models"; + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); // TODO: Fill this out. } ``` @@ -114,10 +115,10 @@ Beginning with the "Codegen" file (`MarkdownDocumentationCodegen.java`), the con These options are some defaults which may require updating. Let's look line-by-line at the config. ```java -outputFolder = "generated-code" + File.separator + "markdown"; +outputFolder = "generated-code" + File.separator + "common-mark"; ``` -This is the default output location. This will be `generated-code/markdown` on non-Windows machines and `generated-code\markdown` on Windows. You may change this to any value you'd like, but a user will almost always provide an output directory. +This is the default output location. This will be `generated-code/common-mark` on non-Windows machines and `generated-code\common-mark` on Windows. You may change this to any value you'd like, but a user will almost always provide an output directory. > When joining paths, always use `File.seperator` @@ -140,10 +141,10 @@ This is the template used for generating API related files. Similar to the above The path is considered relative to `embeddedTemplateDir`, `templateDir`, or a library subdirectory (refer to the Java client generator implementation for a prime example). ```java -embeddedTemplateDir = templateDir = "markdown-documentation"; +embeddedTemplateDir = templateDir = "common-mark-documentation"; ``` -This line sets the embedded and template directories to `markdown-documentation`. The `embeddedTemplateDir` refers to the directory which will exist under `modules/openapi-generator/src/main/resources` and will be published with every release in which your new generator is present. +This line sets the embedded and template directories to `common-mark-documentation`. The `embeddedTemplateDir` refers to the directory which will exist under `modules/openapi-generator/src/main/resources` and will be published with every release in which your new generator is present. The `templateDir` variable refers to the "current" template directory setting, as defined by the user. That is, the user may invoke with `-t` or `--template-directory` (or plugin option variants), and override this directory. @@ -161,7 +162,7 @@ Every templated output from `api.mustache` (registered via `apiTemplateFiles` ab modelPackage = File.separator + "Models"; ``` -Similarly, this sets the packasge for `Models`. +Similarly, this sets the package for `Models`. Every templated output from `model.mustache` (registered via `modelTemplateFiles` above) will end up in the directory defined by `modelPackage` here. @@ -171,7 +172,7 @@ supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); A "supporting file" is an extra file which isn't created once for every operation or model defined in your specification document. It is a single file which may or may not be templated (determined by the extension of the filename). -A supporting file only passes through the Markdown template processor if the filename ends in `.mustache`. +A supporting file only passes through the Mustache template processor if the filename ends in `.mustache`. The path is considered relative to `embeddedTemplateDir`, `templateDir`, or a library subdirectory (refer to the Java client generator implementation for a prime example). @@ -329,7 +330,7 @@ To compile quickly to test this out, you can run `mvn clean package -DskipTests` ### Compile Sample -The `new.sh` script created `bin/markdown-documentation-petstore.sh`: +The `new.sh` script created `bin/common-mark-documentation-petstore.sh`: ```bash #!/bin/sh @@ -359,15 +360,15 @@ then fi # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g markdown -o samples/documentation/petstore/markdown" +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/mark" java ${JAVA_OPTS} -jar ${executable} ${ags} ``` This script is often used to apply default options for generation. A common option in most of these script is to define the template directory as the generator's directory under `resources`. This allows template maintainers to modify and test out template changes which don't require recompilation of the entire project. You'd still need to recompile the project in full if you add or modify behaviors to the generator (such as adding a `CliOption`). -Add `-t modules/openapi-generator/src/main/resources/markdown-documentation` to `ags` line to simplify the evaluation of template-only modifications: +Add `-t modules/openapi-generator/src/main/resources/common-mark-documentation` to `ags` line to simplify the evaluation of template-only modifications: ```diff diff --git a/bin/markdown-documentation-petstore.sh b/bin/markdown-documentation-petstore.sh @@ -377,9 +378,9 @@ index d816771478..94b4ce6d12 100644 @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. - export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" --ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g markdown -o samples/documentation/petstore/markdown" -+ags="$@ generate -t modules/openapi-generator/src/main/resources/markdown-documentation -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g markdown -o samples/documentation/petstore/markdown" + export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +-ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common-mark" ++ags="$@ generate -t modules/openapi-generator/src/main/resources/common-mark-documentation -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/markdown" java ${JAVA_OPTS} -jar ${executable} ${ags} ``` @@ -397,7 +398,7 @@ npm install --global markserv Now, you can serve the output directory directly and test your links: ```bash -markserv samples/documentation/petstore/markdown +markserv samples/documentation/petstore/common/markdown ``` That's it! You've created your first generator! diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index fac1edfe389..4fdb4be1a54 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -243,6 +243,11 @@ slf4j-api ${slf4j-version} + + org.slf4j + slf4j-simple + ${slf4j-version} + org.apache.commons commons-lang3 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index 8a1c158c9f1..c0fa1f667e2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -132,6 +132,9 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; + public static final String SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG = "sortModelPropertiesByRequiredFlag"; + public static final String SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG_DESC = "Sort model properties to place required parameters before optional parameters."; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS = "prependFormOrBodyParameters"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_DESC = "Add form or body parameters to the beginning of the parameter list."; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index a7289087ef5..f8eb675d477 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -19,12 +19,11 @@ package org.openapitools.codegen; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.v3.oas.models.ExternalDocumentation; -import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.*; @JsonIgnoreProperties({"parentModel", "interfaceModels"}) -public class CodegenModel { +public class CodegenModel implements IJsonSchemaValidationProperties { public String parent, parentSchema; public List interfaces; public List allParents; @@ -70,176 +69,57 @@ public class CodegenModel { //The type of the value from additional properties. Used in map like objects. public String additionalPropertiesType; - public String getParent() { - return parent; + private Integer maxProperties; + private Integer minProperties; + private boolean uniqueItems; + private Integer maxItems; + private Integer minItems; + private Integer maxLength; + private Integer minLength; + private boolean exclusiveMinimum; + private boolean exclusiveMaximum; + private String minimum; + private String maximum; + private String pattern; + + public String getAdditionalPropertiesType() { + return additionalPropertiesType; } - public void setParent(String parent) { - this.parent = parent; + public void setAdditionalPropertiesType(String additionalPropertiesType) { + this.additionalPropertiesType = additionalPropertiesType; } - public String getParentSchema() { - return parentSchema; + public Set getAllMandatory() { + return allMandatory; } - public void setParentSchema(String parentSchema) { - this.parentSchema = parentSchema; - } - - public List getInterfaces() { - return interfaces; + public void setAllMandatory(Set allMandatory) { + this.allMandatory = allMandatory; } public List getAllParents() { return allParents; } - public void setInterfaces(List interfaces) { - this.interfaces = interfaces; - } - public void setAllParents(List allParents) { this.allParents = allParents; } - public CodegenModel getParentModel() { - return parentModel; + public List getAllVars() { + return allVars; } - public void setParentModel(CodegenModel parentModel) { - this.parentModel = parentModel; + public void setAllVars(List allVars) { + this.allVars = allVars; } - public List getInterfaceModels() { - return interfaceModels; + public Map getAllowableValues() { + return allowableValues; } - public void setInterfaceModels(List interfaceModels) { - this.interfaceModels = interfaceModels; - } - - public List getChildren() { - return children; - } - - public void setChildren(List children) { - this.children = children; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getClassVarName() { - return classVarName; - } - - public void setClassVarName(String classVarName) { - this.classVarName = classVarName; - } - - public String getModelJson() { - return modelJson; - } - - public void setModelJson(String modelJson) { - this.modelJson = modelJson; - } - - public String getDataType() { - return dataType; - } - - public void setDataType(String dataType) { - this.dataType = dataType; - } - - public String getXmlPrefix() { - return xmlPrefix; - } - - public void setXmlPrefix(String xmlPrefix) { - this.xmlPrefix = xmlPrefix; - } - - public String getXmlNamespace() { - return xmlNamespace; - } - - public void setXmlNamespace(String xmlNamespace) { - this.xmlNamespace = xmlNamespace; - } - - public String getXmlName() { - return xmlName; - } - - public void setXmlName(String xmlName) { - this.xmlName = xmlName; - } - - public String getClassFilename() { - return classFilename; - } - - public void setClassFilename(String classFilename) { - this.classFilename = classFilename; - } - - public String getUnescapedDescription() { - return unescapedDescription; - } - - public void setUnescapedDescription(String unescapedDescription) { - this.unescapedDescription = unescapedDescription; - } - - public CodegenDiscriminator getDiscriminator() { - return discriminator; - } - - public String getDiscriminatorName() { - return discriminator == null ? null : discriminator.getPropertyName(); - } - - public void setDiscriminator(CodegenDiscriminator discriminator) { - this.discriminator = discriminator; - } - - public String getDefaultValue() { - return defaultValue; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; + public void setAllowableValues(Map allowableValues) { + this.allowableValues = allowableValues; } public String getArrayModelType() { @@ -250,20 +130,128 @@ public class CodegenModel { this.arrayModelType = arrayModelType; } - public List getVars() { - return vars; + public List getChildren() { + return children; } - public void setVars(List vars) { - this.vars = vars; + public void setChildren(List children) { + this.children = children; } - public List getRequiredVars() { - return requiredVars; + public String getClassFilename() { + return classFilename; } - public void setRequiredVars(List requiredVars) { - this.requiredVars = requiredVars; + public void setClassFilename(String classFilename) { + this.classFilename = classFilename; + } + + public String getClassVarName() { + return classVarName; + } + + public void setClassVarName(String classVarName) { + this.classVarName = classVarName; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public CodegenDiscriminator getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(CodegenDiscriminator discriminator) { + this.discriminator = discriminator; + } + + public String getDiscriminatorName() { + return discriminator == null ? null : discriminator.getPropertyName(); + } + + public ExternalDocumentation getExternalDocumentation() { + return externalDocumentation; + } + + public void setExternalDocumentation(ExternalDocumentation externalDocumentation) { + this.externalDocumentation = externalDocumentation; + } + + public Set getImports() { + return imports; + } + + public void setImports(Set imports) { + this.imports = imports; + } + + public List getInterfaceModels() { + return interfaceModels; + } + + public void setInterfaceModels(List interfaceModels) { + this.interfaceModels = interfaceModels; + } + + public List getInterfaces() { + return interfaces; + } + + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } + + public Set getMandatory() { + return mandatory; + } + + public void setMandatory(Set mandatory) { + this.mandatory = mandatory; + } + + public String getModelJson() { + return modelJson; + } + + public void setModelJson(String modelJson) { + this.modelJson = modelJson; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; } public List getOptionalVars() { @@ -274,6 +262,158 @@ public class CodegenModel { this.optionalVars = optionalVars; } + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public CodegenModel getParentModel() { + return parentModel; + } + + public void setParentModel(CodegenModel parentModel) { + this.parentModel = parentModel; + } + + public String getParentSchema() { + return parentSchema; + } + + public void setParentSchema(String parentSchema) { + this.parentSchema = parentSchema; + } + + public List getParentVars() { + return parentVars; + } + + public void setParentVars(List parentVars) { + this.parentVars = parentVars; + } + + @Override + public String getPattern() { + return pattern; + } + + @Override + public void setPattern(String pattern) { + this.pattern = pattern; + } + + @Override + public String getMaximum() { + return maximum; + } + + @Override + public void setMaximum(String maximum) { + this.maximum = maximum; + } + + @Override + public String getMinimum() { + return minimum; + } + + @Override + public void setMinimum(String minimum) { + this.minimum = minimum; + } + + @Override + public boolean getExclusiveMaximum() { + return exclusiveMaximum; + } + + @Override + public void setExclusiveMaximum(boolean exclusiveMaximum) { + this.exclusiveMaximum = exclusiveMaximum; + } + + @Override + public boolean getExclusiveMinimum() { + return exclusiveMinimum; + } + + @Override + public void setExclusiveMinimum(boolean exclusiveMinimum) { + this.exclusiveMinimum = exclusiveMinimum; + } + + @Override + public Integer getMinLength() { + return minLength; + } + + @Override + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } + + @Override + public Integer getMaxLength() { + return maxLength; + } + + @Override + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } + + @Override + public Integer getMinItems() { + return minItems; + } + + @Override + public void setMinItems(Integer minItems) { + this.minItems = minItems; + } + + @Override + public Integer getMaxItems() { + return maxItems; + } + + @Override + public void setMaxItems(Integer maxItems) { + this.maxItems = maxItems; + } + + @Override + public boolean getUniqueItems() { + return uniqueItems; + } + + @Override + public void setUniqueItems(boolean uniqueItems) { + this.uniqueItems = uniqueItems; + } + + @Override + public Integer getMinProperties() { + return minProperties; + } + + @Override + public void setMinProperties(Integer minProperties) { + this.minProperties = minProperties; + } + + @Override + public Integer getMaxProperties() { + return maxProperties; + } + + @Override + public void setMaxProperties(Integer maxProperties) { + this.maxProperties = maxProperties; + } + public List getReadOnlyVars() { return readOnlyVars; } @@ -290,68 +430,36 @@ public class CodegenModel { this.readWriteVars = readWriteVars; } - public List getAllVars() { - return allVars; + public List getRequiredVars() { + return requiredVars; } - public void setAllVars(List allVars) { - this.allVars = allVars; + public void setRequiredVars(List requiredVars) { + this.requiredVars = requiredVars; } - public List getParentVars() { - return parentVars; + public String getTitle() { + return title; } - public void setParentVars(List parentVars) { - this.parentVars = parentVars; + public void setTitle(String title) { + this.title = title; } - public Map getAllowableValues() { - return allowableValues; + public String getUnescapedDescription() { + return unescapedDescription; } - public void setAllowableValues(Map allowableValues) { - this.allowableValues = allowableValues; + public void setUnescapedDescription(String unescapedDescription) { + this.unescapedDescription = unescapedDescription; } - public Set getMandatory() { - return mandatory; + public List getVars() { + return vars; } - public void setMandatory(Set mandatory) { - this.mandatory = mandatory; - } - - public Set getAllMandatory() { - return allMandatory; - } - - public void setAllMandatory(Set allMandatory) { - this.allMandatory = allMandatory; - } - - public Set getImports() { - return imports; - } - - public void setImports(Set imports) { - this.imports = imports; - } - - public boolean isEmptyVars() { - return emptyVars; - } - - public void setEmptyVars(boolean emptyVars) { - this.emptyVars = emptyVars; - } - - public ExternalDocumentation getExternalDocumentation() { - return externalDocumentation; - } - - public void setExternalDocumentation(ExternalDocumentation externalDocumentation) { - this.externalDocumentation = externalDocumentation; + public void setVars(List vars) { + this.vars = vars; } public Map getVendorExtensions() { @@ -362,12 +470,208 @@ public class CodegenModel { this.vendorExtensions = vendorExtensions; } - public String getAdditionalPropertiesType() { - return additionalPropertiesType; + public String getXmlName() { + return xmlName; } - public void setAdditionalPropertiesType(String additionalPropertiesType) { - this.additionalPropertiesType = additionalPropertiesType; + public void setXmlName(String xmlName) { + this.xmlName = xmlName; + } + + public String getXmlNamespace() { + return xmlNamespace; + } + + public void setXmlNamespace(String xmlNamespace) { + this.xmlNamespace = xmlNamespace; + } + + public String getXmlPrefix() { + return xmlPrefix; + } + + public void setXmlPrefix(String xmlPrefix) { + this.xmlPrefix = xmlPrefix; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CodegenModel)) return false; + CodegenModel that = (CodegenModel) o; + return isAlias == that.isAlias && + isString == that.isString && + isInteger == that.isInteger && + isLong == that.isLong && + isNumber == that.isNumber && + isNumeric == that.isNumeric && + isFloat == that.isFloat && + isDouble == that.isDouble && + hasVars == that.hasVars && + emptyVars == that.emptyVars && + hasMoreModels == that.hasMoreModels && + hasEnums == that.hasEnums && + isEnum == that.isEnum && + isNullable == that.isNullable && + hasRequired == that.hasRequired && + hasOptional == that.hasOptional && + isArrayModel == that.isArrayModel && + hasChildren == that.hasChildren && + isMapModel == that.isMapModel && + hasOnlyReadOnly == that.hasOnlyReadOnly && + getUniqueItems() == that.getUniqueItems() && + getExclusiveMinimum() == that.getExclusiveMinimum() && + getExclusiveMaximum() == that.getExclusiveMaximum() && + Objects.equals(parent, that.parent) && + Objects.equals(parentSchema, that.parentSchema) && + Objects.equals(interfaces, that.interfaces) && + Objects.equals(allParents, that.allParents) && + Objects.equals(parentModel, that.parentModel) && + Objects.equals(interfaceModels, that.interfaceModels) && + Objects.equals(children, that.children) && + Objects.equals(anyOf, that.anyOf) && + Objects.equals(oneOf, that.oneOf) && + Objects.equals(allOf, that.allOf) && + Objects.equals(name, that.name) && + Objects.equals(classname, that.classname) && + Objects.equals(title, that.title) && + Objects.equals(description, that.description) && + Objects.equals(classVarName, that.classVarName) && + Objects.equals(modelJson, that.modelJson) && + Objects.equals(dataType, that.dataType) && + Objects.equals(xmlPrefix, that.xmlPrefix) && + Objects.equals(xmlNamespace, that.xmlNamespace) && + Objects.equals(xmlName, that.xmlName) && + Objects.equals(classFilename, that.classFilename) && + Objects.equals(unescapedDescription, that.unescapedDescription) && + Objects.equals(discriminator, that.discriminator) && + Objects.equals(defaultValue, that.defaultValue) && + Objects.equals(arrayModelType, that.arrayModelType) && + Objects.equals(vars, that.vars) && + Objects.equals(allVars, that.allVars) && + Objects.equals(requiredVars, that.requiredVars) && + Objects.equals(optionalVars, that.optionalVars) && + Objects.equals(readOnlyVars, that.readOnlyVars) && + Objects.equals(readWriteVars, that.readWriteVars) && + Objects.equals(parentVars, that.parentVars) && + Objects.equals(allowableValues, that.allowableValues) && + Objects.equals(mandatory, that.mandatory) && + Objects.equals(allMandatory, that.allMandatory) && + Objects.equals(imports, that.imports) && + Objects.equals(externalDocumentation, that.externalDocumentation) && + Objects.equals(vendorExtensions, that.vendorExtensions) && + Objects.equals(additionalPropertiesType, that.additionalPropertiesType) && + Objects.equals(getMaxProperties(), that.getMaxProperties()) && + Objects.equals(getMinProperties(), that.getMinProperties()) && + Objects.equals(getMaxItems(), that.getMaxItems()) && + Objects.equals(getMinItems(), that.getMinItems()) && + Objects.equals(getMaxLength(), that.getMaxLength()) && + Objects.equals(getMinLength(), that.getMinLength()) && + Objects.equals(getMinimum(), that.getMinimum()) && + Objects.equals(getMaximum(), that.getMaximum()) && + Objects.equals(getPattern(), that.getPattern()); + } + + @Override + public int hashCode() { + return Objects.hash(getParent(), getParentSchema(), getInterfaces(), getAllParents(), getParentModel(), + getInterfaceModels(), getChildren(), anyOf, oneOf, allOf, getName(), getClassname(), getTitle(), + getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(), + getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(), + getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, + getVars(), getAllVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(), + getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars, + isEmptyVars(), hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArrayModel, + hasChildren, isMapModel, hasOnlyReadOnly, getExternalDocumentation(), getVendorExtensions(), + getAdditionalPropertiesType(), getMaxProperties(), getMinProperties(), getUniqueItems(), getMaxItems(), + getMinItems(), getMaxLength(), getMinLength(), getExclusiveMinimum(), getExclusiveMaximum(), getMinimum(), + getMaximum(), getPattern()); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CodegenModel{"); + sb.append("parent='").append(parent).append('\''); + sb.append(", parentSchema='").append(parentSchema).append('\''); + sb.append(", interfaces=").append(interfaces); + sb.append(", allParents=").append(allParents); + sb.append(", parentModel=").append(parentModel); + sb.append(", interfaceModels=").append(interfaceModels); + sb.append(", children=").append(children); + sb.append(", anyOf=").append(anyOf); + sb.append(", oneOf=").append(oneOf); + sb.append(", allOf=").append(allOf); + sb.append(", name='").append(name).append('\''); + sb.append(", classname='").append(classname).append('\''); + sb.append(", title='").append(title).append('\''); + sb.append(", description='").append(description).append('\''); + sb.append(", classVarName='").append(classVarName).append('\''); + sb.append(", modelJson='").append(modelJson).append('\''); + sb.append(", dataType='").append(dataType).append('\''); + sb.append(", xmlPrefix='").append(xmlPrefix).append('\''); + sb.append(", xmlNamespace='").append(xmlNamespace).append('\''); + sb.append(", xmlName='").append(xmlName).append('\''); + sb.append(", classFilename='").append(classFilename).append('\''); + sb.append(", unescapedDescription='").append(unescapedDescription).append('\''); + sb.append(", discriminator=").append(discriminator); + sb.append(", defaultValue='").append(defaultValue).append('\''); + sb.append(", arrayModelType='").append(arrayModelType).append('\''); + sb.append(", isAlias=").append(isAlias); + sb.append(", isString=").append(isString); + sb.append(", isInteger=").append(isInteger); + sb.append(", isLong=").append(isLong); + sb.append(", isNumber=").append(isNumber); + sb.append(", isNumeric=").append(isNumeric); + sb.append(", isFloat=").append(isFloat); + sb.append(", isDouble=").append(isDouble); + sb.append(", vars=").append(vars); + sb.append(", allVars=").append(allVars); + sb.append(", requiredVars=").append(requiredVars); + sb.append(", optionalVars=").append(optionalVars); + sb.append(", readOnlyVars=").append(readOnlyVars); + sb.append(", readWriteVars=").append(readWriteVars); + sb.append(", parentVars=").append(parentVars); + sb.append(", allowableValues=").append(allowableValues); + sb.append(", mandatory=").append(mandatory); + sb.append(", allMandatory=").append(allMandatory); + sb.append(", imports=").append(imports); + sb.append(", hasVars=").append(hasVars); + sb.append(", emptyVars=").append(emptyVars); + sb.append(", hasMoreModels=").append(hasMoreModels); + sb.append(", hasEnums=").append(hasEnums); + sb.append(", isEnum=").append(isEnum); + sb.append(", isNullable=").append(isNullable); + sb.append(", hasRequired=").append(hasRequired); + sb.append(", hasOptional=").append(hasOptional); + sb.append(", isArrayModel=").append(isArrayModel); + sb.append(", hasChildren=").append(hasChildren); + sb.append(", isMapModel=").append(isMapModel); + sb.append(", hasOnlyReadOnly=").append(hasOnlyReadOnly); + sb.append(", externalDocumentation=").append(externalDocumentation); + sb.append(", vendorExtensions=").append(vendorExtensions); + sb.append(", additionalPropertiesType='").append(additionalPropertiesType).append('\''); + sb.append(", maxProperties=").append(maxProperties); + sb.append(", minProperties=").append(minProperties); + sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", maxItems=").append(maxItems); + sb.append(", minItems=").append(minItems); + sb.append(", maxLength=").append(maxLength); + sb.append(", minLength=").append(minLength); + sb.append(", exclusiveMinimum=").append(exclusiveMinimum); + sb.append(", exclusiveMaximum=").append(exclusiveMaximum); + sb.append(", minimum='").append(minimum).append('\''); + sb.append(", maximum='").append(maximum).append('\''); + sb.append(", pattern='").append(pattern).append('\''); + sb.append('}'); + return sb.toString(); + } + + public boolean isEmptyVars() { + return emptyVars; + } + + public void setEmptyVars(boolean emptyVars) { + this.emptyVars = emptyVars; } /** @@ -450,149 +754,4 @@ public class CodegenModel { } } } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CodegenModel that = (CodegenModel) o; - return isAlias == that.isAlias && - isString == that.isString && - isInteger == that.isInteger && - isLong == that.isLong && - isNumber == that.isNumber && - isNumeric == that.isNumeric && - isFloat == that.isFloat && - isDouble == that.isDouble && - hasVars == that.hasVars && - emptyVars == that.emptyVars && - hasMoreModels == that.hasMoreModels && - hasEnums == that.hasEnums && - isEnum == that.isEnum && - isNullable == that.isNullable && - hasRequired == that.hasRequired && - hasOptional == that.hasOptional && - isArrayModel == that.isArrayModel && - hasChildren == that.hasChildren && - isMapModel == that.isMapModel && - hasOnlyReadOnly == that.hasOnlyReadOnly && - Objects.equals(parent, that.parent) && - Objects.equals(parentSchema, that.parentSchema) && - Objects.equals(interfaces, that.interfaces) && - Objects.equals(allParents, that.allParents) && - Objects.equals(parentModel, that.parentModel) && - Objects.equals(interfaceModels, that.interfaceModels) && - Objects.equals(children, that.children) && - Objects.equals(anyOf, that.anyOf) && - Objects.equals(oneOf, that.oneOf) && - Objects.equals(allOf, that.allOf) && - Objects.equals(name, that.name) && - Objects.equals(classname, that.classname) && - Objects.equals(title, that.title) && - Objects.equals(description, that.description) && - Objects.equals(classVarName, that.classVarName) && - Objects.equals(modelJson, that.modelJson) && - Objects.equals(dataType, that.dataType) && - Objects.equals(xmlPrefix, that.xmlPrefix) && - Objects.equals(xmlNamespace, that.xmlNamespace) && - Objects.equals(xmlName, that.xmlName) && - Objects.equals(classFilename, that.classFilename) && - Objects.equals(unescapedDescription, that.unescapedDescription) && - Objects.equals(discriminator, that.discriminator) && - Objects.equals(defaultValue, that.defaultValue) && - Objects.equals(arrayModelType, that.arrayModelType) && - Objects.equals(vars, that.vars) && - Objects.equals(allVars, that.allVars) && - Objects.equals(requiredVars, that.requiredVars) && - Objects.equals(optionalVars, that.optionalVars) && - Objects.equals(readOnlyVars, that.readOnlyVars) && - Objects.equals(readWriteVars, that.readWriteVars) && - Objects.equals(parentVars, that.parentVars) && - Objects.equals(allowableValues, that.allowableValues) && - Objects.equals(mandatory, that.mandatory) && - Objects.equals(allMandatory, that.allMandatory) && - Objects.equals(imports, that.imports) && - Objects.equals(externalDocumentation, that.externalDocumentation) && - Objects.equals(vendorExtensions, that.vendorExtensions) && - Objects.equals(additionalPropertiesType, that.additionalPropertiesType); - } - - @Override - public int hashCode() { - - return Objects.hash(parent, parentSchema, interfaces, allParents, parentModel, interfaceModels, children, - anyOf, oneOf, allOf, name, classname, title, description, classVarName, modelJson, dataType, - xmlPrefix, xmlNamespace, xmlName, classFilename, unescapedDescription, discriminator, defaultValue, - arrayModelType, isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, - vars, allVars, requiredVars, optionalVars, readOnlyVars, readWriteVars, parentVars, allowableValues, - mandatory, allMandatory, imports, hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, isNullable, - hasRequired, hasOptional, isArrayModel, hasChildren, isMapModel, hasOnlyReadOnly, - externalDocumentation, vendorExtensions, additionalPropertiesType); - } - - @Override - public String toString() { - final StringBuffer sb = new StringBuffer("CodegenModel{"); - sb.append("parent='").append(parent).append('\''); - sb.append(", parentSchema='").append(parentSchema).append('\''); - sb.append(", interfaces=").append(interfaces); - sb.append(", allParents=").append(allParents); - sb.append(", parentModel=").append(parentModel); - sb.append(", interfaceModels=").append(interfaceModels); - sb.append(", children=").append(children); - sb.append(", anyOf=").append(anyOf); - sb.append(", oneOf=").append(oneOf); - sb.append(", allOf=").append(allOf); - sb.append(", name='").append(name).append('\''); - sb.append(", classname='").append(classname).append('\''); - sb.append(", title='").append(title).append('\''); - sb.append(", description='").append(description).append('\''); - sb.append(", classVarName='").append(classVarName).append('\''); - sb.append(", modelJson='").append(modelJson).append('\''); - sb.append(", dataType='").append(dataType).append('\''); - sb.append(", xmlPrefix='").append(xmlPrefix).append('\''); - sb.append(", xmlNamespace='").append(xmlNamespace).append('\''); - sb.append(", xmlName='").append(xmlName).append('\''); - sb.append(", classFilename='").append(classFilename).append('\''); - sb.append(", unescapedDescription='").append(unescapedDescription).append('\''); - sb.append(", discriminator=").append(discriminator); - sb.append(", defaultValue='").append(defaultValue).append('\''); - sb.append(", arrayModelType='").append(arrayModelType).append('\''); - sb.append(", isAlias=").append(isAlias); - sb.append(", isString=").append(isString); - sb.append(", isInteger=").append(isInteger); - sb.append(", isLong=").append(isLong); - sb.append(", isNumber=").append(isNumber); - sb.append(", isNumeric=").append(isNumeric); - sb.append(", isFloat=").append(isFloat); - sb.append(", isDouble=").append(isDouble); - sb.append(", vars=").append(vars); - sb.append(", allVars=").append(allVars); - sb.append(", requiredVars=").append(requiredVars); - sb.append(", optionalVars=").append(optionalVars); - sb.append(", readOnlyVars=").append(readOnlyVars); - sb.append(", readWriteVars=").append(readWriteVars); - sb.append(", parentVars=").append(parentVars); - sb.append(", allowableValues=").append(allowableValues); - sb.append(", mandatory=").append(mandatory); - sb.append(", allMandatory=").append(allMandatory); - sb.append(", imports=").append(imports); - sb.append(", hasVars=").append(hasVars); - sb.append(", emptyVars=").append(emptyVars); - sb.append(", hasMoreModels=").append(hasMoreModels); - sb.append(", hasEnums=").append(hasEnums); - sb.append(", isEnum=").append(isEnum); - sb.append(", isNullable=").append(isNullable); - sb.append(", hasRequired=").append(hasRequired); - sb.append(", hasOptional=").append(hasOptional); - sb.append(", isArrayModel=").append(isArrayModel); - sb.append(", hasChildren=").append(hasChildren); - sb.append(", isMapModel=").append(isMapModel); - sb.append(", hasOnlyReadOnly=").append(hasOnlyReadOnly); - sb.append(", externalDocumentation=").append(externalDocumentation); - sb.append(", vendorExtensions=").append(vendorExtensions); - sb.append(", additionalPropertiesType='").append(additionalPropertiesType).append('\''); - sb.append('}'); - return sb.toString(); - } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 15979f7ad61..14fb30a8617 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -17,13 +17,9 @@ package org.openapitools.codegen; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; -public class CodegenParameter { +public class CodegenParameter implements IJsonSchemaValidationProperties { public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, isContainer, secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode; @@ -43,10 +39,231 @@ public class CodegenParameter { public CodegenProperty mostInnerItems; public Map vendorExtensions = new HashMap(); public boolean hasValidation; + public boolean isNullable; + /** + * Determines whether this parameter is mandatory. If the parameter is in "path", + * this property is required and its value MUST be true. Otherwise, the property + * MAY be included and its default value is false. + */ + public boolean required; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17. + */ + public String maximum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17 + */ + public boolean exclusiveMaximum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ + public String minimum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ + public boolean exclusiveMinimum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor26 + */ + public Integer maxLength; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor29 + */ + public Integer minLength; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor33 + */ + public String pattern; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor42 + */ + public Integer maxItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor45 + */ + public Integer minItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor49 + */ + public boolean uniqueItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor14 + */ + public Number multipleOf; + private Integer maxProperties; + private Integer minProperties; + + public CodegenParameter copy() { + CodegenParameter output = new CodegenParameter(); + output.isFile = this.isFile; + output.hasMore = this.hasMore; + output.isContainer = this.isContainer; + output.secondaryParam = this.secondaryParam; + output.baseName = this.baseName; + output.paramName = this.paramName; + output.dataType = this.dataType; + output.datatypeWithEnum = this.datatypeWithEnum; + output.enumName = this.enumName; + output.dataFormat = this.dataFormat; + output.collectionFormat = this.collectionFormat; + output.isCollectionFormatMulti = this.isCollectionFormatMulti; + output.isPrimitiveType = this.isPrimitiveType; + output.isModel = this.isModel; + output.description = this.description; + output.unescapedDescription = this.unescapedDescription; + output.baseType = this.baseType; + output.isFormParam = this.isFormParam; + output.isQueryParam = this.isQueryParam; + output.isPathParam = this.isPathParam; + output.isHeaderParam = this.isHeaderParam; + output.isCookieParam = this.isCookieParam; + output.isBodyParam = this.isBodyParam; + output.required = this.required; + output.maximum = this.maximum; + output.exclusiveMaximum = this.exclusiveMaximum; + output.minimum = this.minimum; + output.exclusiveMinimum = this.exclusiveMinimum; + output.maxLength = this.maxLength; + output.minLength = this.minLength; + output.pattern = this.pattern; + output.maxItems = this.maxItems; + output.minItems = this.minItems; + output.uniqueItems = this.uniqueItems; + output.multipleOf = this.multipleOf; + output.jsonSchema = this.jsonSchema; + output.defaultValue = this.defaultValue; + output.example = this.example; + output.isEnum = this.isEnum; + output.maxProperties = this.maxProperties; + output.minProperties = this.minProperties; + output.maximum = this.maximum; + output.minimum = this.minimum; + output.pattern = this.pattern; + + if (this._enum != null) { + output._enum = new ArrayList(this._enum); + } + if (this.allowableValues != null) { + output.allowableValues = new HashMap(this.allowableValues); + } + if (this.items != null) { + output.items = this.items; + } + if (this.mostInnerItems != null) { + output.mostInnerItems = this.mostInnerItems; + } + if (this.vendorExtensions != null) { + output.vendorExtensions = new HashMap(this.vendorExtensions); + } + output.hasValidation = this.hasValidation; + output.isNullable = this.isNullable; + output.isBinary = this.isBinary; + output.isByteArray = this.isByteArray; + output.isString = this.isString; + output.isNumeric = this.isNumeric; + output.isInteger = this.isInteger; + output.isLong = this.isLong; + output.isDouble = this.isDouble; + output.isFloat = this.isFloat; + output.isNumber = this.isNumber; + output.isBoolean = this.isBoolean; + output.isDate = this.isDate; + output.isDateTime = this.isDateTime; + output.isUuid = this.isUuid; + output.isUri = this.isUri; + output.isEmail = this.isEmail; + output.isFreeFormObject = this.isFreeFormObject; + output.isListContainer = this.isListContainer; + output.isMapContainer = this.isMapContainer; + output.isExplode = this.isExplode; + output.style = this.style; + + return output; + } + + @Override + public int hashCode() { + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, isContainer, secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isListContainer, isMapContainer, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), multipleOf); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CodegenParameter)) return false; + CodegenParameter that = (CodegenParameter) o; + return isFormParam == that.isFormParam && + isQueryParam == that.isQueryParam && + isPathParam == that.isPathParam && + isHeaderParam == that.isHeaderParam && + isCookieParam == that.isCookieParam && + isBodyParam == that.isBodyParam && + hasMore == that.hasMore && + isContainer == that.isContainer && + secondaryParam == that.secondaryParam && + isCollectionFormatMulti == that.isCollectionFormatMulti && + isPrimitiveType == that.isPrimitiveType && + isModel == that.isModel && + isExplode == that.isExplode && + isString == that.isString && + isNumeric == that.isNumeric && + isInteger == that.isInteger && + isLong == that.isLong && + isNumber == that.isNumber && + isFloat == that.isFloat && + isDouble == that.isDouble && + isByteArray == that.isByteArray && + isBinary == that.isBinary && + isBoolean == that.isBoolean && + isDate == that.isDate && + isDateTime == that.isDateTime && + isUuid == that.isUuid && + isUri == that.isUri && + isEmail == that.isEmail && + isFreeFormObject == that.isFreeFormObject && + isListContainer == that.isListContainer && + isMapContainer == that.isMapContainer && + isFile == that.isFile && + isEnum == that.isEnum && + hasValidation == that.hasValidation && + isNullable == that.isNullable && + required == that.required && + getExclusiveMaximum() == that.getExclusiveMaximum() && + getExclusiveMinimum() == that.getExclusiveMinimum() && + getUniqueItems() == that.getUniqueItems() && + Objects.equals(baseName, that.baseName) && + Objects.equals(paramName, that.paramName) && + Objects.equals(dataType, that.dataType) && + Objects.equals(datatypeWithEnum, that.datatypeWithEnum) && + Objects.equals(dataFormat, that.dataFormat) && + Objects.equals(collectionFormat, that.collectionFormat) && + Objects.equals(description, that.description) && + Objects.equals(unescapedDescription, that.unescapedDescription) && + Objects.equals(baseType, that.baseType) && + Objects.equals(defaultValue, that.defaultValue) && + Objects.equals(enumName, that.enumName) && + Objects.equals(style, that.style) && + Objects.equals(example, that.example) && + Objects.equals(jsonSchema, that.jsonSchema) && + Objects.equals(_enum, that._enum) && + Objects.equals(allowableValues, that.allowableValues) && + Objects.equals(items, that.items) && + Objects.equals(mostInnerItems, that.mostInnerItems) && + Objects.equals(vendorExtensions, that.vendorExtensions) && + Objects.equals(getMaxProperties(), that.getMaxProperties()) && + Objects.equals(getMinProperties(), that.getMinProperties()) && + Objects.equals(getMaximum(), that.getMaximum()) && + Objects.equals(getMinimum(), that.getMinimum()) && + Objects.equals(getMaxLength(), that.getMaxLength()) && + Objects.equals(getMinLength(), that.getMinLength()) && + Objects.equals(getPattern(), that.getPattern()) && + Objects.equals(getMaxItems(), that.getMaxItems()) && + Objects.equals(getMinItems(), that.getMinItems()) && + Objects.equals(multipleOf, that.multipleOf); + } @Override public String toString() { - final StringBuffer sb = new StringBuffer("CodegenParameter{"); + final StringBuilder sb = new StringBuilder("CodegenParameter{"); sb.append("isFormParam=").append(isFormParam); sb.append(", isQueryParam=").append(isQueryParam); sb.append(", isPathParam=").append(isPathParam); @@ -100,6 +317,8 @@ public class CodegenParameter { sb.append(", mostInnerItems=").append(mostInnerItems); sb.append(", vendorExtensions=").append(vendorExtensions); sb.append(", hasValidation=").append(hasValidation); + sb.append(", maxProperties=").append(maxProperties); + sb.append(", minProperties=").append(minProperties); sb.append(", isNullable=").append(isNullable); sb.append(", required=").append(required); sb.append(", maximum='").append(maximum).append('\''); @@ -118,226 +337,123 @@ public class CodegenParameter { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CodegenParameter that = (CodegenParameter) o; - return isFormParam == that.isFormParam && - isQueryParam == that.isQueryParam && - isPathParam == that.isPathParam && - isHeaderParam == that.isHeaderParam && - isCookieParam == that.isCookieParam && - isBodyParam == that.isBodyParam && - hasMore == that.hasMore && - isContainer == that.isContainer && - secondaryParam == that.secondaryParam && - isCollectionFormatMulti == that.isCollectionFormatMulti && - isPrimitiveType == that.isPrimitiveType && - isModel == that.isModel && - isExplode == that.isExplode && - isString == that.isString && - isNumeric == that.isNumeric && - isInteger == that.isInteger && - isLong == that.isLong && - isNumber == that.isNumber && - isFloat == that.isFloat && - isDouble == that.isDouble && - isByteArray == that.isByteArray && - isBinary == that.isBinary && - isBoolean == that.isBoolean && - isDate == that.isDate && - isDateTime == that.isDateTime && - isUuid == that.isUuid && - isUri == that.isUri && - isEmail == that.isEmail && - isFreeFormObject == that.isFreeFormObject && - isListContainer == that.isListContainer && - isMapContainer == that.isMapContainer && - isFile == that.isFile && - isEnum == that.isEnum && - hasValidation == that.hasValidation && - isNullable == that.isNullable && - required == that.required && - exclusiveMaximum == that.exclusiveMaximum && - exclusiveMinimum == that.exclusiveMinimum && - uniqueItems == that.uniqueItems && - Objects.equals(baseName, that.baseName) && - Objects.equals(paramName, that.paramName) && - Objects.equals(dataType, that.dataType) && - Objects.equals(datatypeWithEnum, that.datatypeWithEnum) && - Objects.equals(dataFormat, that.dataFormat) && - Objects.equals(collectionFormat, that.collectionFormat) && - Objects.equals(description, that.description) && - Objects.equals(unescapedDescription, that.unescapedDescription) && - Objects.equals(baseType, that.baseType) && - Objects.equals(defaultValue, that.defaultValue) && - Objects.equals(enumName, that.enumName) && - Objects.equals(style, that.style) && - Objects.equals(example, that.example) && - Objects.equals(jsonSchema, that.jsonSchema) && - Objects.equals(_enum, that._enum) && - Objects.equals(allowableValues, that.allowableValues) && - Objects.equals(items, that.items) && - Objects.equals(mostInnerItems, that.mostInnerItems) && - Objects.equals(vendorExtensions, that.vendorExtensions) && - Objects.equals(maximum, that.maximum) && - Objects.equals(minimum, that.minimum) && - Objects.equals(maxLength, that.maxLength) && - Objects.equals(minLength, that.minLength) && - Objects.equals(pattern, that.pattern) && - Objects.equals(maxItems, that.maxItems) && - Objects.equals(minItems, that.minItems) && - Objects.equals(multipleOf, that.multipleOf); + public String getPattern() { + return pattern; } @Override - public int hashCode() { - - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, - isContainer, secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, - paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, - baseType, defaultValue, enumName, style, example, jsonSchema, isString, isNumeric, isInteger, isLong, - isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, - isEmail, isFreeFormObject, isListContainer, isMapContainer, isFile, isEnum, _enum, allowableValues, - items, mostInnerItems, vendorExtensions, hasValidation, isNullable, required, maximum, - exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, maxItems, minItems, - uniqueItems, multipleOf); + public void setPattern(String pattern) { + this.pattern = pattern; } - public boolean isNullable; + @Override + public String getMaximum() { + return maximum; + } - /** - * Determines whether this parameter is mandatory. If the parameter is in "path", - * this property is required and its value MUST be true. Otherwise, the property - * MAY be included and its default value is false. - */ - public boolean required; + @Override + public void setMaximum(String maximum) { + this.maximum = maximum; + } - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor17. - */ - public String maximum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor17 - */ - public boolean exclusiveMaximum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor21 - */ - public String minimum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor21 - */ - public boolean exclusiveMinimum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor26 - */ - public Integer maxLength; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor29 - */ - public Integer minLength; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor33 - */ - public String pattern; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor42 - */ - public Integer maxItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor45 - */ - public Integer minItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor49 - */ - public boolean uniqueItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor14 - */ - public Number multipleOf; + @Override + public String getMinimum() { + return minimum; + } - public CodegenParameter copy() { - CodegenParameter output = new CodegenParameter(); - output.isFile = this.isFile; - output.hasMore = this.hasMore; - output.isContainer = this.isContainer; - output.secondaryParam = this.secondaryParam; - output.baseName = this.baseName; - output.paramName = this.paramName; - output.dataType = this.dataType; - output.datatypeWithEnum = this.datatypeWithEnum; - output.enumName = this.enumName; - output.dataFormat = this.dataFormat; - output.collectionFormat = this.collectionFormat; - output.isCollectionFormatMulti = this.isCollectionFormatMulti; - output.isPrimitiveType = this.isPrimitiveType; - output.isModel = this.isModel; - output.description = this.description; - output.unescapedDescription = this.unescapedDescription; - output.baseType = this.baseType; - output.isFormParam = this.isFormParam; - output.isQueryParam = this.isQueryParam; - output.isPathParam = this.isPathParam; - output.isHeaderParam = this.isHeaderParam; - output.isCookieParam = this.isCookieParam; - output.isBodyParam = this.isBodyParam; - output.required = this.required; - output.maximum = this.maximum; - output.exclusiveMaximum = this.exclusiveMaximum; - output.minimum = this.minimum; - output.exclusiveMinimum = this.exclusiveMinimum; - output.maxLength = this.maxLength; - output.minLength = this.minLength; - output.pattern = this.pattern; - output.maxItems = this.maxItems; - output.minItems = this.minItems; - output.uniqueItems = this.uniqueItems; - output.multipleOf = this.multipleOf; - output.jsonSchema = this.jsonSchema; - output.defaultValue = this.defaultValue; - output.example = this.example; - output.isEnum = this.isEnum; - if (this._enum != null) { - output._enum = new ArrayList(this._enum); - } - if (this.allowableValues != null) { - output.allowableValues = new HashMap(this.allowableValues); - } - if (this.items != null) { - output.items = this.items; - } - if (this.mostInnerItems != null) { - output.mostInnerItems = this.mostInnerItems; - } - if (this.vendorExtensions != null) { - output.vendorExtensions = new HashMap(this.vendorExtensions); - } - output.hasValidation = this.hasValidation; - output.isNullable = this.isNullable; - output.isBinary = this.isBinary; - output.isByteArray = this.isByteArray; - output.isString = this.isString; - output.isNumeric = this.isNumeric; - output.isInteger = this.isInteger; - output.isLong = this.isLong; - output.isDouble = this.isDouble; - output.isFloat = this.isFloat; - output.isNumber = this.isNumber; - output.isBoolean = this.isBoolean; - output.isDate = this.isDate; - output.isDateTime = this.isDateTime; - output.isUuid = this.isUuid; - output.isUri = this.isUri; - output.isEmail = this.isEmail; - output.isFreeFormObject = this.isFreeFormObject; - output.isListContainer = this.isListContainer; - output.isMapContainer = this.isMapContainer; - output.isExplode = this.isExplode; - output.style = this.style; + @Override + public void setMinimum(String minimum) { + this.minimum = minimum; + } - return output; + @Override + public boolean getExclusiveMaximum() { + return exclusiveMaximum; + } + + @Override + public void setExclusiveMaximum(boolean exclusiveMaximum) { + this.exclusiveMaximum = exclusiveMaximum; + } + + @Override + public boolean getExclusiveMinimum() { + return exclusiveMinimum; + } + + @Override + public void setExclusiveMinimum(boolean exclusiveMinimum) { + this.exclusiveMinimum = exclusiveMinimum; + } + + @Override + public Integer getMinLength() { + return minLength; + } + + @Override + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } + + @Override + public Integer getMaxLength() { + return maxLength; + } + + @Override + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } + + @Override + public Integer getMinItems() { + return minItems; + } + + @Override + public void setMinItems(Integer minItems) { + this.minItems = minItems; + } + + @Override + public Integer getMaxItems() { + return maxItems; + } + + @Override + public void setMaxItems(Integer maxItems) { + this.maxItems = maxItems; + } + + @Override + public boolean getUniqueItems() { + return uniqueItems; + } + + @Override + public void setUniqueItems(boolean uniqueItems) { + this.uniqueItems = uniqueItems; + } + + @Override + public Integer getMinProperties() { + return minProperties; + } + + @Override + public void setMinProperties(Integer minProperties) { + this.minProperties = minProperties; + } + + @Override + public Integer getMaxProperties() { + return maxProperties; + } + + @Override + public void setMaxProperties(Integer maxProperties) { + this.maxProperties = maxProperties; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index 16edb14adf8..e9877eefafa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -19,7 +19,7 @@ package org.openapitools.codegen; import java.util.*; -public class CodegenProperty implements Cloneable { +public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties { public String openApiType, baseName, complexType, getter, setter, description, dataType, datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, containerType, title; @@ -51,12 +51,32 @@ public class CodegenProperty implements Cloneable { public String maximum; public boolean exclusiveMinimum; public boolean exclusiveMaximum; - public boolean hasMore, required, secondaryParam; + public boolean hasMore; + public boolean required; + public boolean secondaryParam; public boolean hasMoreNonReadOnly; // for model constructor, true if next property is not readonly - public boolean isPrimitiveType, isModel, isContainer; - public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, - isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject; - public boolean isListContainer, isMapContainer; + public boolean isPrimitiveType; + public boolean isModel; + public boolean isContainer; + public boolean isString; + public boolean isNumeric; + public boolean isInteger; + public boolean isLong; + public boolean isNumber; + public boolean isFloat; + public boolean isDouble; + public boolean isByteArray; + public boolean isBinary; + public boolean isFile; + public boolean isBoolean; + public boolean isDate; + public boolean isDateTime; + public boolean isUuid; + public boolean isUri; + public boolean isEmail; + public boolean isFreeFormObject; + public boolean isListContainer; + public boolean isMapContainer; public boolean isEnum; public boolean isReadOnly; public boolean isWriteOnly; @@ -78,6 +98,10 @@ public class CodegenProperty implements Cloneable { public Integer maxItems; public Integer minItems; + private Integer maxProperties; + private Integer minProperties; + private boolean uniqueItems; + // XML public boolean isXmlAttribute = false; public String xmlPrefix; @@ -231,26 +255,32 @@ public class CodegenProperty implements Cloneable { this.unescapedDescription = unescapedDescription; } + @Override public Integer getMaxLength() { return maxLength; } + @Override public void setMaxLength(Integer maxLength) { this.maxLength = maxLength; } + @Override public Integer getMinLength() { return minLength; } + @Override public void setMinLength(Integer minLength) { this.minLength = minLength; } + @Override public String getPattern() { return pattern; } + @Override public void setPattern(String pattern) { this.pattern = pattern; } @@ -271,26 +301,37 @@ public class CodegenProperty implements Cloneable { this.jsonSchema = jsonSchema; } + @Override public String getMinimum() { return minimum; } + @Override public void setMinimum(String minimum) { this.minimum = minimum; } + @Override + public boolean getExclusiveMaximum() { + return this.exclusiveMaximum; + } + + @Override public String getMaximum() { return maximum; } + @Override public void setMaximum(String maximum) { this.maximum = maximum; } + @Override public boolean getExclusiveMinimum() { return exclusiveMinimum; } + @Override public void setExclusiveMinimum(boolean exclusiveMinimum) { this.exclusiveMinimum = exclusiveMinimum; } @@ -299,6 +340,7 @@ public class CodegenProperty implements Cloneable { return exclusiveMaximum; } + @Override public void setExclusiveMaximum(boolean exclusiveMaximum) { this.exclusiveMaximum = exclusiveMaximum; } @@ -371,18 +413,22 @@ public class CodegenProperty implements Cloneable { this.enumName = enumName; } + @Override public Integer getMaxItems() { return maxItems; } + @Override public void setMaxItems(Integer maxItems) { this.maxItems = maxItems; } + @Override public Integer getMinItems() { return minItems; } + @Override public void setMinItems(Integer minItems) { this.minItems = minItems; } @@ -437,10 +483,39 @@ public class CodegenProperty implements Cloneable { } } + @Override + public boolean getUniqueItems() { + return uniqueItems; + } + + @Override + public void setUniqueItems(boolean uniqueItems) { + this.uniqueItems = uniqueItems; + } + + @Override + public Integer getMinProperties() { + return minProperties; + } + + @Override + public void setMinProperties(Integer minProperties) { + this.minProperties = minProperties; + } + + @Override + public Integer getMaxProperties() { + return maxProperties; + } + + @Override + public void setMaxProperties(Integer maxProperties) { + this.maxProperties = maxProperties; + } @Override public String toString() { - final StringBuffer sb = new StringBuffer("CodegenProperty{"); + final StringBuilder sb = new StringBuilder("CodegenProperty{"); sb.append("openApiType='").append(openApiType).append('\''); sb.append(", baseName='").append(baseName).append('\''); sb.append(", complexType='").append(complexType).append('\''); @@ -513,6 +588,9 @@ public class CodegenProperty implements Cloneable { sb.append(", enumName='").append(enumName).append('\''); sb.append(", maxItems=").append(maxItems); sb.append(", minItems=").append(minItems); + sb.append(", maxProperties=").append(maxProperties); + sb.append(", minProperties=").append(minProperties); + sb.append(", uniqueItems=").append(uniqueItems); sb.append(", isXmlAttribute=").append(isXmlAttribute); sb.append(", xmlPrefix='").append(xmlPrefix).append('\''); sb.append(", xmlName='").append(xmlName).append('\''); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 511c0fc7b60..b814f2207f3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -19,15 +19,31 @@ package org.openapitools.codegen; import java.util.*; -public class CodegenResponse { +public class CodegenResponse implements IJsonSchemaValidationProperties { public final List headers = new ArrayList(); - public String code, message; + public String code; + public String message; public boolean hasMore; public List> examples; - public String dataType, baseType, containerType, pattern; + public String dataType; + public String baseType; + public String containerType; public boolean hasHeaders; - public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, - isDateTime, isUuid, isEmail, isModel, isFreeFormObject; + public boolean isString; + public boolean isNumeric; + public boolean isInteger; + public boolean isLong; + public boolean isNumber; + public boolean isFloat; + public boolean isDouble; + public boolean isByteArray; + public boolean isBoolean; + public boolean isDate; + public boolean isDateTime; + public boolean isUuid; + public boolean isEmail; + public boolean isModel; + public boolean isFreeFormObject; public boolean isDefault; public boolean simpleType; public boolean primitiveType; @@ -38,9 +54,27 @@ public class CodegenResponse { public Object schema; public String jsonSchema; public Map vendorExtensions = new HashMap(); + private Integer maxProperties; + private Integer minProperties; + private boolean uniqueItems; + private Integer maxItems; + private Integer minItems; + private Integer maxLength; + private Integer minLength; + private boolean exclusiveMinimum; + private boolean exclusiveMaximum; + private String minimum; + private String maximum; + public String pattern; - public boolean isWildcard() { - return "0".equals(code) || "default".equals(code); + @Override + public int hashCode() { + return Objects.hash(headers, code, message, hasMore, examples, dataType, baseType, containerType, hasHeaders, + isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, + isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isDefault, simpleType, primitiveType, + isMapContainer, isListContainer, isBinary, isFile, schema, jsonSchema, vendorExtensions, + getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(), + getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern()); } @Override @@ -79,30 +113,152 @@ public class CodegenResponse { Objects.equals(dataType, that.dataType) && Objects.equals(baseType, that.baseType) && Objects.equals(containerType, that.containerType) && - Objects.equals(pattern, that.pattern) && Objects.equals(schema, that.schema) && Objects.equals(jsonSchema, that.jsonSchema) && - Objects.equals(vendorExtensions, that.vendorExtensions); + Objects.equals(vendorExtensions, that.vendorExtensions) && + Objects.equals(getMaxProperties(), that.getMaxProperties()) && + Objects.equals(getMinProperties(), that.getMinProperties()) && + Objects.equals(uniqueItems, that.uniqueItems) && + Objects.equals(getMaxItems(), that.getMaxItems()) && + Objects.equals(getMinItems(), that.getMinItems()) && + Objects.equals(getMaxLength(), that.getMaxLength()) && + Objects.equals(getMinLength(), that.getMinLength()) && + Objects.equals(exclusiveMinimum, that.exclusiveMinimum) && + Objects.equals(exclusiveMaximum, that.exclusiveMaximum) && + Objects.equals(getMinimum(), that.getMinimum()) && + Objects.equals(getMaximum(), that.getMaximum()) && + Objects.equals(getPattern(), that.getPattern()); } @Override - public int hashCode() { - return Objects.hash(headers, code, message, hasMore, examples, dataType, baseType, containerType, pattern, - hasHeaders, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, - isBoolean, isDate, isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isDefault, simpleType, - primitiveType, isMapContainer, isListContainer, isBinary, isFile, schema, jsonSchema, vendorExtensions); + public String getPattern() { + return pattern; + } + + @Override + public void setPattern(String pattern) { + this.pattern = pattern; + } + + @Override + public String getMaximum() { + return maximum; + } + + @Override + public void setMaximum(String maximum) { + this.maximum = maximum; + } + + @Override + public String getMinimum() { + return minimum; + } + + @Override + public void setMinimum(String minimum) { + this.minimum = minimum; + } + + @Override + public boolean getExclusiveMaximum() { + return exclusiveMaximum; + } + + @Override + public void setExclusiveMaximum(boolean exclusiveMaximum) { + this.exclusiveMaximum = exclusiveMaximum; + } + + @Override + public boolean getExclusiveMinimum() { + return exclusiveMinimum; + } + + @Override + public void setExclusiveMinimum(boolean exclusiveMinimum) { + this.exclusiveMinimum = exclusiveMinimum; + } + + @Override + public Integer getMinLength() { + return minLength; + } + + @Override + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } + + @Override + public Integer getMaxLength() { + return maxLength; + } + + @Override + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } + + @Override + public Integer getMinItems() { + return minItems; + } + + @Override + public void setMinItems(Integer minItems) { + this.minItems = minItems; + } + + @Override + public Integer getMaxItems() { + return maxItems; + } + + @Override + public void setMaxItems(Integer maxItems) { + this.maxItems = maxItems; + } + + @Override + public boolean getUniqueItems() { + return uniqueItems; + } + + @Override + public void setUniqueItems(boolean uniqueItems) { + this.uniqueItems = uniqueItems; + } + + @Override + public Integer getMinProperties() { + return minProperties; + } + + @Override + public void setMinProperties(Integer minProperties) { + this.minProperties = minProperties; + } + + @Override + public Integer getMaxProperties() { + return maxProperties; + } + + @Override + public void setMaxProperties(Integer maxProperties) { + this.maxProperties = maxProperties; } @Override public String toString() { - final StringBuffer sb = new StringBuffer("CodegenResponse{"); + final StringBuilder sb = new StringBuilder("CodegenResponse{"); sb.append("headers=").append(headers); sb.append(", code='").append(code).append('\''); sb.append(", message='").append(message).append('\''); sb.append(", hasMore=").append(hasMore); sb.append(", examples=").append(examples); sb.append(", dataType='").append(dataType).append('\''); - sb.append(", pattern='").append(pattern).append('\''); sb.append(", baseType='").append(baseType).append('\''); sb.append(", containerType='").append(containerType).append('\''); sb.append(", hasHeaders=").append(hasHeaders); @@ -131,7 +287,25 @@ public class CodegenResponse { sb.append(", schema=").append(schema); sb.append(", jsonSchema='").append(jsonSchema).append('\''); sb.append(", vendorExtensions=").append(vendorExtensions); + sb.append(", maxProperties=").append(maxProperties); + sb.append(", minProperties=").append(minProperties); + sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", maxItems=").append(maxItems); + sb.append(", minItems=").append(minItems); + sb.append(", maxLength=").append(maxLength); + sb.append(", minLength=").append(minLength); + sb.append(", exclusiveMinimum=").append(exclusiveMinimum); + sb.append(", exclusiveMaximum=").append(exclusiveMaximum); + sb.append(", minimum='").append(minimum).append('\''); + sb.append(", maximum='").append(maximum).append('\''); + sb.append(", pattern='").append(pattern).append('\''); sb.append('}'); return sb.toString(); } + + // this is used in templates. Do not remove it. + @SuppressWarnings("unused") + public boolean isWildcard() { + return "0".equals(code) || "default".equals(code); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index f35967ea2e9..a7b1dfdcb73 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -109,6 +109,7 @@ public class DefaultCodegen implements CodegenConfig { protected Map supportedLibraries = new LinkedHashMap(); protected String library; protected Boolean sortParamsByRequiredFlag = true; + protected Boolean sortModelPropertiesByRequiredFlag = false; protected Boolean ensureUniqueParams = true; protected Boolean allowUnicodeIdentifiers = false; protected String gitHost, gitUserId, gitRepoId, releaseNote; @@ -165,6 +166,11 @@ public class DefaultCodegen implements CodegenConfig { .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); } + if (additionalProperties.containsKey(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG)) { + this.setSortModelPropertiesByRequiredFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG).toString())); + } + if (additionalProperties.containsKey(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS)) { this.setPrependFormOrBodyParameters(Boolean.valueOf(additionalProperties .get(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS).toString())); @@ -258,13 +264,12 @@ public class DefaultCodegen implements CodegenConfig { } /** - * Loop through all models to update different flags (e.g. isSelfReference), children models, etc + * Index all CodegenModels by model name. * * @param objs Map of models - * @return maps of models with various updates + * @return map of all models indexed by names */ - public Map updateAllModels(Map objs) { - // Index all CodegenModels by model name. + public Map getAllModels(Map objs) { Map allModels = new HashMap(); for (Entry entry : objs.entrySet()) { String modelName = toModelName(entry.getKey()); @@ -275,6 +280,17 @@ public class DefaultCodegen implements CodegenConfig { allModels.put(modelName, cm); } } + return allModels; + } + + /** + * Loop through all models to update different flags (e.g. isSelfReference), children models, etc + * + * @param objs Map of models + * @return maps of models with various updates + */ + public Map updateAllModels(Map objs) { + Map allModels = getAllModels(objs); // Fix up all parent and interface CodegenModel references. for (CodegenModel cm : allModels.values()) { @@ -336,7 +352,7 @@ public class DefaultCodegen implements CodegenConfig { public void setCircularReferences(Map models) { final Map> dependencyMap = models.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> getModelDependencies(entry.getValue()))); - + models.keySet().forEach(name -> setCircularReferencesOnProperties(name, dependencyMap)); } @@ -854,6 +870,14 @@ public class DefaultCodegen implements CodegenConfig { this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; } + public Boolean getSortModelPropertiesByRequiredFlag() { + return sortModelPropertiesByRequiredFlag; + } + + public void setSortModelPropertiesByRequiredFlag(Boolean sortModelPropertiesByRequiredFlag) { + this.sortModelPropertiesByRequiredFlag = sortModelPropertiesByRequiredFlag; + } + public Boolean getPrependFormOrBodyParameters() { return prependFormOrBodyParameters; } @@ -1164,6 +1188,8 @@ public class DefaultCodegen implements CodegenConfig { cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, + CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); // name formatting options @@ -1858,10 +1884,12 @@ public class DefaultCodegen implements CodegenConfig { m.allVars = new ArrayList(); if (composed.getAllOf() != null) { int modelImplCnt = 0; // only one inline object allowed in a ComposedModel - for (Schema innerSchema : composed.getAllOf()) { // TOOD need to work with anyOf, oneOf as well - if (m.discriminator == null) { + int modelDiscriminators = 0; // only one discriminator allowed in a ComposedModel + for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well + if (m.discriminator == null && innerSchema.getDiscriminator() != null) { LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", name); - m.discriminator = createDiscriminator(name, schema); + m.discriminator = createDiscriminator(name, innerSchema); + modelDiscriminators++; } if (innerSchema.getXml() != null) { @@ -1869,6 +1897,9 @@ public class DefaultCodegen implements CodegenConfig { m.xmlNamespace = innerSchema.getXml().getNamespace(); m.xmlName = innerSchema.getXml().getName(); } + if (modelDiscriminators > 1) { + LOGGER.error("Allof composed schema is inheriting >1 discriminator. Only use one discriminator: {}", composed); + } if (modelImplCnt++ > 1) { LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); @@ -1972,6 +2003,10 @@ public class DefaultCodegen implements CodegenConfig { addAdditionPropertiesToCodeGenModel(m, schema); m.isMapModel = true; } else if (ModelUtils.isIntegerSchema(schema)) { // integer type + // NOTE: Integral schemas as CodegenModel is a rare use case and may be removed at a later date. + // Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty. + ModelUtils.syncValidationProperties(schema, m); + m.isNumeric = Boolean.TRUE; if (ModelUtils.isLongSchema(schema)) { // int64/long format m.isLong = Boolean.TRUE; @@ -1979,8 +2014,14 @@ public class DefaultCodegen implements CodegenConfig { m.isInteger = Boolean.TRUE; } } else if (ModelUtils.isStringSchema(schema)) { + // NOTE: String schemas as CodegenModel is a rare use case and may be removed at a later date. + // Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty. + ModelUtils.syncValidationProperties(schema, m); m.isString = Boolean.TRUE; } else if (ModelUtils.isNumberSchema(schema)) { + // NOTE: Number schemas as CodegenModel is a rare use case and may be removed at a later date. + // Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty. + ModelUtils.syncValidationProperties(schema, m); m.isNumeric = Boolean.TRUE; if (ModelUtils.isFloatSchema(schema)) { // float m.isFloat = Boolean.TRUE; @@ -2009,6 +2050,17 @@ public class DefaultCodegen implements CodegenConfig { } } + if (sortModelPropertiesByRequiredFlag) { + Collections.sort(m.vars, new Comparator() { + @Override + public int compare(CodegenProperty one, CodegenProperty another) { + if (one.required == another.required) return 0; + else if (one.required) return -1; + else return 1; + } + }); + } + return m; } @@ -2122,6 +2174,9 @@ public class DefaultCodegen implements CodegenConfig { p = ModelUtils.unaliasSchema(this.openAPI, p); CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); + + ModelUtils.syncValidationProperties(p, property); + property.name = toVarName(name); property.baseName = name; if (p.getType() == null) { @@ -2926,6 +2981,21 @@ public class DefaultCodegen implements CodegenConfig { */ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); + + if (response.getContent() != null && response.getContent().size() > 0) { + // Ensure validation properties from a target schema are persisted on CodegenResponse. + // This ignores any edge case where different schemas have different validations because we don't + // have a way to indicate a preference for response schema and are effective 1:1. + Schema contentSchema = null; + for (MediaType mt : response.getContent().values()) { + if (contentSchema != null) break; + contentSchema = mt.getSchema(); + } + if (contentSchema != null) { + ModelUtils.syncValidationProperties(contentSchema, r); + } + } + if ("default".equals(responseCode)) { r.code = "0"; } else { @@ -2939,7 +3009,7 @@ public class DefaultCodegen implements CodegenConfig { } r.schema = responseSchema; if (responseSchema != null && responseSchema.getPattern() != null) { - r.pattern = toRegularExpression(responseSchema.getPattern()); + r.setPattern(toRegularExpression(responseSchema.getPattern())); } r.message = escapeText(response.getDescription()); @@ -3118,6 +3188,21 @@ public class DefaultCodegen implements CodegenConfig { */ public CodegenParameter fromParameter(Parameter parameter, Set imports) { CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + + if (parameter.getContent() != null && parameter.getContent().size() > 0) { + // Ensure validation properties from a target schema are persisted on CodegenParameter. + // This ignores any edge case where different schemas have different validations because we don't + // have a way to indicate a preference for parameter schema and are effective 1:1. + Schema contentSchema = null; + for (MediaType mt : parameter.getContent().values()) { + if (contentSchema != null) break; + contentSchema = mt.getSchema(); + } + if (contentSchema != null) { + ModelUtils.syncValidationProperties(contentSchema, codegenParameter); + } + } + codegenParameter.baseName = parameter.getName(); codegenParameter.description = escapeText(parameter.getDescription()); codegenParameter.unescapedDescription = parameter.getDescription(); @@ -3471,6 +3556,9 @@ public class DefaultCodegen implements CodegenConfig { cs.isCode = cs.isPassword = cs.isApplication = cs.isImplicit = false; cs.isBasicBasic = cs.isBasicBearer = false; cs.scheme = securityScheme.getScheme(); + if (securityScheme.getExtensions() != null) { + cs.vendorExtensions.putAll(securityScheme.getExtensions()); + } if (SecurityScheme.Type.APIKEY.equals(securityScheme.getType())) { cs.isBasic = cs.isOAuth = false; @@ -4785,6 +4873,8 @@ public class DefaultCodegen implements CodegenConfig { LOGGER.debug("Debugging fromFormProperty {}: {}", name, propertySchema); CodegenProperty codegenProperty = fromProperty(name, propertySchema); + ModelUtils.syncValidationProperties(propertySchema, codegenProperty); + codegenParameter.isFormParam = Boolean.TRUE; codegenParameter.baseName = codegenProperty.baseName; codegenParameter.paramName = toParamName((codegenParameter.baseName)); @@ -4886,6 +4976,8 @@ public class DefaultCodegen implements CodegenConfig { } schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + ModelUtils.syncValidationProperties(schema, codegenParameter); + if (ModelUtils.isMapSchema(schema)) { Schema inner = ModelUtils.getAdditionalProperties(schema); if (inner == null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java new file mode 100644 index 00000000000..8a4f9cea99a --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java @@ -0,0 +1,41 @@ +package org.openapitools.codegen; + +import java.math.BigDecimal; + +public interface IJsonSchemaValidationProperties { + String getPattern(); + void setPattern(String pattern); + + String getMaximum(); + void setMaximum(String maximum); + + String getMinimum(); + void setMinimum(String minimum); + + boolean getExclusiveMaximum(); + void setExclusiveMaximum(boolean exclusiveMaximum); + + boolean getExclusiveMinimum(); + void setExclusiveMinimum(boolean exclusiveMinimum); + + Integer getMinLength(); + void setMinLength(Integer minLength); + + Integer getMaxLength(); + void setMaxLength(Integer maxLength); + + Integer getMinItems(); + void setMinItems(Integer minItems); + + Integer getMaxItems(); + void setMaxItems(Integer maxItems); + + boolean getUniqueItems(); + void setUniqueItems(boolean uniqueItems); + + Integer getMinProperties(); + void setMinProperties(Integer minProperties); + + Integer getMaxProperties(); + void setMaxProperties(Integer maxProperties); +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java index 606e0564c44..ed895fd5ac1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java @@ -71,6 +71,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co public AbstractKotlinCodegen() { super(); supportsInheritance = true; + setSortModelPropertiesByRequiredFlag(true); languageSpecificPrimitives = new HashSet(Arrays.asList( "kotlin.Byte", @@ -228,6 +229,8 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co cliOptions.add(new CliOption(CodegenConstants.PARCELIZE_MODELS, CodegenConstants.PARCELIZE_MODELS_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG_DESC)); cliOptions.add(CliOption.newBoolean(MODEL_MUTABLE, MODEL_MUTABLE_DESC, false)); } @@ -456,6 +459,9 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co additionalProperties.put(CodegenConstants.NON_PUBLIC_API, nonPublicApi); } + additionalProperties.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, getSortParamsByRequiredFlag()); + additionalProperties.put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, getSortModelPropertiesByRequiredFlag()); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage()); additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index cf290dc0de4..bd14a843e64 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -337,7 +337,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf @Override public String toParamName(String name) { // should be the same as variable name - if (name.matches("^\\d.*")) { + if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } name = name.replaceAll("-","_"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 314caff8ea2..8930d2d6b53 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -173,9 +173,13 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a Dart (1.x (deprecated) or 2.x) client library."; } + protected void defaultProcessOpts() { + super.processOpts(); + } + @Override public void processOpts() { - super.processOpts(); + defaultProcessOpts(); if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) { LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java index 0729817c489..764a0ddac9e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java @@ -16,6 +16,7 @@ package org.openapitools.codegen.languages; +import java.util.HashMap; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; @@ -44,9 +45,10 @@ import static org.openapitools.codegen.utils.StringUtils.underscore; public class DartDioClientCodegen extends DartClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(DartDioClientCodegen.class); - private static final String NULLABLE_FIELDS = "nullableFields"; + public static final String NULLABLE_FIELDS = "nullableFields"; private static final String IS_FORMAT_JSON = "jsonFormat"; private static final String CLIENT_NAME = "clientName"; + public static final String DATE_LIBRARY = "dateLibrary"; private static Set modelToIgnore = new HashSet<>(); @@ -62,18 +64,26 @@ public class DartDioClientCodegen extends DartClientCodegen { private static final String SERIALIZATION_JSON = "json"; private boolean nullableFields = true; + private String dateLibrary = "core"; public DartDioClientCodegen() { super(); browserClient = false; outputFolder = "generated-code/dart-dio"; - embeddedTemplateDir = templateDir = "dart-dio"; + embeddedTemplateDir = "dart-dio"; + this.setTemplateDir(embeddedTemplateDir); //no tests at this time modelTestTemplateFiles.clear(); apiTestTemplateFiles.clear(); cliOptions.add(new CliOption(NULLABLE_FIELDS, "Is the null fields should be in the JSON payload")); + CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use").defaultValue(this.getDateLibrary()); + Map dateOptions = new HashMap<>(); + dateOptions.put("core", "Dart core library (DateTime)"); + dateOptions.put("timemachine", "Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing."); + dateLibrary.setEnum(dateOptions); + cliOptions.add(dateLibrary); typeMapping.put("file", "Uint8List"); typeMapping.put("binary", "Uint8List"); @@ -84,6 +94,23 @@ public class DartDioClientCodegen extends DartClientCodegen { importMapping.put("Uint8List", "dart:typed_data"); } + public String getDateLibrary() { + return dateLibrary; + } + + public void setDateLibrary(String library) { + this.dateLibrary = library; + } + + public boolean getNullableFields() { + return nullableFields; + } + + public void setNullableFields(boolean nullableFields) { + this.nullableFields = nullableFields; + } + + @Override public String getName() { return "dart-dio"; @@ -94,6 +121,10 @@ public class DartDioClientCodegen extends DartClientCodegen { return "Generates a Dart Dio client library."; } + @Override public void setBrowserClient(boolean browserClient) { + super.browserClient = browserClient; + } + @Override public String toDefaultValue(Schema p) { if (ModelUtils.isMapSchema(p)) { @@ -105,11 +136,10 @@ public class DartDioClientCodegen extends DartClientCodegen { } @Override - public String escapeReservedWord(String name) { - if (this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return "_" + name; + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + //super.addAdditionPropertiesToCodeGenModel(codegenModel, schema); + codegenModel.additionalPropertiesType = getSchemaType(ModelUtils.getAdditionalProperties(schema)); + addImport(codegenModel, codegenModel.additionalPropertiesType); } @Override @@ -117,12 +147,10 @@ public class DartDioClientCodegen extends DartClientCodegen { if (name.length() == 0) { return "empty"; } - if ("number".equalsIgnoreCase(datatype) || - "int".equalsIgnoreCase(datatype)) { + if ("number".equalsIgnoreCase(datatype) || "int".equalsIgnoreCase(datatype)) { name = "Number" + name; } name = camelize(name, true); - // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); @@ -130,22 +158,24 @@ public class DartDioClientCodegen extends DartClientCodegen { return name; } - @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { - //super.addAdditionPropertiesToCodeGenModel(codegenModel, schema); - codegenModel.additionalPropertiesType = getSchemaType(ModelUtils.getAdditionalProperties(schema)); - addImport(codegenModel, codegenModel.additionalPropertiesType); - } - @Override public void processOpts() { + defaultProcessOpts(); + if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) { LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)"); LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); } + if (additionalProperties.containsKey(BROWSER_CLIENT)) { + this.setBrowserClient(convertPropertyToBooleanAndWriteBack(BROWSER_CLIENT)); + } else { + //not set, use to be passed to template + additionalProperties.put(BROWSER_CLIENT, browserClient); + } + if (additionalProperties.containsKey(NULLABLE_FIELDS)) { - nullableFields = convertPropertyToBooleanAndWriteBack(NULLABLE_FIELDS); + this.setNullableFields(convertPropertyToBooleanAndWriteBack(NULLABLE_FIELDS)); } else { //not set, use to be passed to template additionalProperties.put(NULLABLE_FIELDS, nullableFields); @@ -189,6 +219,9 @@ public class DartDioClientCodegen extends DartClientCodegen { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } + if (additionalProperties.containsKey(DATE_LIBRARY)) { + this.setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString()); + } // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); @@ -201,6 +234,24 @@ public class DartDioClientCodegen extends DartClientCodegen { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + if ("core".equals(dateLibrary)) { + additionalProperties.put("core", "true"); + typeMapping.put("Date", "DateTime"); + typeMapping.put("date", "DateTime"); + importMapping.put("DateTime", "DateTime"); + importMapping.put("OffsetDateTime", "DateTime"); + } else if ("timemachine".equals(dateLibrary)) { + additionalProperties.put("timeMachine", "true"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("Date", "LocalDate"); + typeMapping.put("DateTime", "OffsetDateTime"); + typeMapping.put("datetime", "OffsetDateTime"); + importMapping.put("LocalDate", "package:time_machine/time_machine.dart"); + importMapping.put("OffsetDateTime", "package:time_machine/time_machine.dart"); + supportingFiles.add(new SupportingFile("local_date_serializer.mustache", libFolder, "local_date_serializer.dart")); + + } } @Override @@ -321,4 +372,6 @@ public class DartDioClientCodegen extends DartClientCodegen { return objs; } + + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java index 0dd404e52a1..88cf8535b4b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java @@ -113,6 +113,7 @@ public class DartJaguarClientCodegen extends DartClientCodegen { @Override public void processOpts() { + defaultProcessOpts(); if (additionalProperties.containsKey(NULLABLE_FIELDS)) { nullableFields = convertPropertyToBooleanAndWriteBack(NULLABLE_FIELDS); } else { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 2f463f51a57..363a76928cb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -29,6 +29,7 @@ import org.openapitools.codegen.SupportingFile; import java.io.File; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -36,16 +37,20 @@ import java.util.stream.Stream; public class KotlinClientCodegen extends AbstractKotlinCodegen { protected static final String JVM = "jvm"; + protected static final String JVM_OKHTTP = "jvm-okhttp"; protected static final String JVM_OKHTTP4 = "jvm-okhttp4"; protected static final String JVM_OKHTTP3 = "jvm-okhttp3"; + protected static final String JVM_RETROFIT2 = "jvm-retrofit2"; protected static final String MULTIPLATFORM = "multiplatform"; public static final String DATE_LIBRARY = "dateLibrary"; + public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; public static final String COLLECTION_TYPE = "collectionType"; protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal"; protected String dateLibrary = DateLibrary.JAVA8.value; + protected String requestDateConverter = RequestDateConverter.TO_STRING.value; protected String collectionType = CollectionType.ARRAY.value; public enum DateLibrary { @@ -60,6 +65,17 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { } } + public enum RequestDateConverter { + TO_STRING("toString"), + TO_JSON("toJson"); + + public final String value; + + RequestDateConverter(String value) { + this.value = value; + } + } + public enum CollectionType { ARRAY("array"), LIST("list"); @@ -112,6 +128,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { supportedLibraries.put(JVM_OKHTTP4, "[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0."); supportedLibraries.put(JVM_OKHTTP3, "Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0."); + supportedLibraries.put(JVM_RETROFIT2, "Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2."); supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0."); CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use"); @@ -119,6 +136,14 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { libraryOption.setDefault(JVM_OKHTTP4); cliOptions.add(libraryOption); setLibrary(JVM_OKHTTP4); + + CliOption requestDateConverter = new CliOption(REQUEST_DATE_CONVERTER, "JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)"); + Map requestDateConverterOptions = new HashMap<>(); + requestDateConverterOptions.put(RequestDateConverter.TO_STRING.value, "[DEFAULT] Use the 'toString'-method of the date-time object to retrieve the related string representation."); + requestDateConverterOptions.put(RequestDateConverter.TO_JSON.value, "Date formater option using a json converter."); + requestDateConverter.setEnum(requestDateConverterOptions); + requestDateConverter.setDefault(this.requestDateConverter); + cliOptions.add(requestDateConverter); } public CodegenType getTag() { @@ -137,6 +162,10 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { this.dateLibrary = library; } + public void setRequestDateConverter(String converter) { + this.requestDateConverter = converter; + } + public void setCollectionType(String collectionType) { this.collectionType = collectionType; } @@ -157,116 +186,30 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString()); } - // common (jvm/multiplatform) supporting files - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ApiAbstractions.kt.mustache", infrastructureFolder, "ApiAbstractions.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt")); - - if (isJVMLibrary()) { - additionalProperties.put(JVM, true); - - if (JVM_OKHTTP4.equals(getLibrary())) { - additionalProperties.put(JVM_OKHTTP4, true); - } else if (JVM_OKHTTP3.equals(getLibrary())) { - additionalProperties.put(JVM_OKHTTP3, true); - } - - supportedLibraries.put(JVM, "A workaround to use the same template folder for both 'jvm-okhttp3' and 'jvm-okhttp4'."); - setLibrary(JVM); - - // jvm specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/ApplicationDelegates.kt.mustache", infrastructureFolder, "ApplicationDelegates.kt")); - supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ResponseExtensions.kt.mustache", infrastructureFolder, "ResponseExtensions.kt")); - supportingFiles.add(new SupportingFile("infrastructure/Serializer.kt.mustache", infrastructureFolder, "Serializer.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ApiInfrastructureResponse.kt.mustache", infrastructureFolder, "ApiInfrastructureResponse.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); - supportingFiles.add(new SupportingFile("infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); - supportingFiles.add(new SupportingFile("infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt")); - if (getSerializationLibrary() == SERIALIZATION_LIBRARY_TYPE.gson) { - supportingFiles.add(new SupportingFile("infrastructure/DateAdapter.kt.mustache", infrastructureFolder, - "DateAdapter.kt")); - } - - } else if (MULTIPLATFORM.equals(getLibrary())) { - additionalProperties.put(MULTIPLATFORM, true); - setDateLibrary(DateLibrary.STRING.value); - - // multiplatform default includes - defaultIncludes.add("io.ktor.client.request.forms.InputProvider"); - defaultIncludes.add(packageName + ".infrastructure.Base64ByteArray"); - defaultIncludes.add(packageName + ".infrastructure.OctetByteArray"); - - // multiplatform type mapping - typeMapping.put("number", "kotlin.Double"); - typeMapping.put("file", "OctetByteArray"); - typeMapping.put("binary", "OctetByteArray"); - typeMapping.put("ByteArray", "Base64ByteArray"); - typeMapping.put("object", "kotlin.String"); // kotlin.Any not serializable - - // multiplatform import mapping - importMapping.put("BigDecimal", "kotlin.Double"); - importMapping.put("UUID", "kotlin.String"); - importMapping.put("URI", "kotlin.String"); - importMapping.put("InputProvider", "io.ktor.client.request.forms.InputProvider"); - importMapping.put("File", packageName + ".infrastructure.OctetByteArray"); - importMapping.put("Timestamp", "kotlin.String"); - importMapping.put("LocalDateTime", "kotlin.String"); - importMapping.put("LocalDate", "kotlin.String"); - importMapping.put("LocalTime", "kotlin.String"); - importMapping.put("Base64ByteArray", packageName + ".infrastructure.Base64ByteArray"); - importMapping.put("OctetByteArray", packageName + ".infrastructure.OctetByteArray"); - - // multiplatform specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/Base64ByteArray.kt.mustache", infrastructureFolder, "Base64ByteArray.kt")); - supportingFiles.add(new SupportingFile("infrastructure/Bytes.kt.mustache", infrastructureFolder, "Bytes.kt")); - supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt")); - supportingFiles.add(new SupportingFile("infrastructure/OctetByteArray.kt.mustache", infrastructureFolder, "OctetByteArray.kt")); - - // multiplatform specific auth - final String authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/"); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt")); - supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt")); - supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt")); - - // multiplatform specific testing files - supportingFiles.add(new SupportingFile("commonTest/Coroutine.kt.mustache", "src/commonTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("iosTest/Coroutine.kt.mustache", "src/iosTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("jsTest/Coroutine.kt.mustache", "src/jsTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("jvmTest/Coroutine.kt.mustache", "src/jvmTest/kotlin/util", "Coroutine.kt")); - - // gradle wrapper supporting files - supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); - supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); - supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.properties")); - supportingFiles.add(new SupportingFile("gradle-wrapper.jar", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.jar")); + if (additionalProperties.containsKey(REQUEST_DATE_CONVERTER)) { + setRequestDateConverter(additionalProperties.get(REQUEST_DATE_CONVERTER).toString()); } - // date library processing - if (DateLibrary.THREETENBP.value.equals(dateLibrary)) { - additionalProperties.put(DateLibrary.THREETENBP.value, true); - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "LocalDateTime"); - importMapping.put("LocalDate", "org.threeten.bp.LocalDate"); - importMapping.put("LocalDateTime", "org.threeten.bp.LocalDateTime"); - defaultIncludes.add("org.threeten.bp.LocalDate"); - defaultIncludes.add("org.threeten.bp.LocalDateTime"); - } else if (DateLibrary.STRING.value.equals(dateLibrary)) { - typeMapping.put("date-time", "kotlin.String"); - typeMapping.put("date", "kotlin.String"); - typeMapping.put("Date", "kotlin.String"); - typeMapping.put("DateTime", "kotlin.String"); - } else if (DateLibrary.JAVA8.value.equals(dateLibrary)) { - additionalProperties.put(DateLibrary.JAVA8.value, true); + commonSupportingFiles(); + + switch (getLibrary()) { + case JVM_OKHTTP3: + case JVM_OKHTTP4: + processJVMOkHttpLibrary(infrastructureFolder); + break; + case JVM_RETROFIT2: + processJVMRetrofit2Library(infrastructureFolder); + break; + case MULTIPLATFORM: + processMultiplatformLibrary(infrastructureFolder); + break; + default: + break; } + processDateLibrary(); + processRequestDateConverter(); + if (additionalProperties.containsKey(COLLECTION_TYPE)) { setCollectionType(additionalProperties.get(COLLECTION_TYPE).toString()); } @@ -276,11 +219,172 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { typeMapping.put("list", "kotlin.collections.List"); additionalProperties.put("isList", true); } - } - private boolean isJVMLibrary() { - return getLibrary() != null && (getLibrary().contains(JVM_OKHTTP4) || getLibrary().contains(JVM_OKHTTP3)); + private void processDateLibrary() { + DateLibrary dateLibraryEnum = DateLibrary.valueOf(dateLibrary.toUpperCase(Locale.ROOT)); + switch (dateLibraryEnum) { + case THREETENBP: + processThreeTeBpDate(); + break; + case STRING: + processStringDate(); + break; + case JAVA8: + processJava8Date(); + break; + default: + break; + } + } + + private void processRequestDateConverter() { + if (RequestDateConverter.TO_JSON.value.equals(requestDateConverter)) { + additionalProperties.put(RequestDateConverter.TO_JSON.value, true); + } else if (RequestDateConverter.TO_STRING.value.equals(requestDateConverter)) { + additionalProperties.put(RequestDateConverter.TO_STRING.value, true); + } + } + + private void processThreeTeBpDate() { + additionalProperties.put(DateLibrary.THREETENBP.value, true); + typeMapping.put("date", "LocalDate"); + typeMapping.put("DateTime", "LocalDateTime"); + importMapping.put("LocalDate", "org.threeten.bp.LocalDate"); + importMapping.put("LocalDateTime", "org.threeten.bp.LocalDateTime"); + defaultIncludes.add("org.threeten.bp.LocalDate"); + defaultIncludes.add("org.threeten.bp.LocalDateTime"); + } + + private void processStringDate() { + typeMapping.put("date-time", "kotlin.String"); + typeMapping.put("date", "kotlin.String"); + typeMapping.put("Date", "kotlin.String"); + typeMapping.put("DateTime", "kotlin.String"); + } + + private void processJava8Date() { + additionalProperties.put(DateLibrary.JAVA8.value, true); + } + + private void processJVMRetrofit2Library(String infrastructureFolder) { + additionalProperties.put(JVM, true); + additionalProperties.put(JVM_RETROFIT2, true); + supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); + supportingFiles.add(new SupportingFile("infrastructure/CollectionFormats.kt.mustache", infrastructureFolder, "CollectionFormats.kt")); + addSupportingSerializerAdapters(infrastructureFolder); + } + + private void addSupportingSerializerAdapters(final String infrastructureFolder) { + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/Serializer.kt.mustache", infrastructureFolder, "Serializer.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); + + switch (getSerializationLibrary()) { + case moshi: + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt")); + break; + + case gson: + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/DateAdapter.kt.mustache", infrastructureFolder, "DateAdapter.kt")); + break; + } + } + + private void processJVMOkHttpLibrary(final String infrastructureFolder) { + commonJvmMultiplatformSupportingFiles(infrastructureFolder); + addSupportingSerializerAdapters(infrastructureFolder); + + additionalProperties.put(JVM, true); + additionalProperties.put(JVM_OKHTTP, true); + + if (JVM_OKHTTP4.equals(getLibrary())) { + additionalProperties.put(JVM_OKHTTP4, true); + } else if (JVM_OKHTTP3.equals(getLibrary())) { + additionalProperties.put(JVM_OKHTTP3, true); + } + + supportedLibraries.put(JVM_OKHTTP, "A workaround to use the same template folder for both 'jvm-okhttp3' and 'jvm-okhttp4'."); + setLibrary(JVM_OKHTTP); + + // jvm specific supporting files + supportingFiles.add(new SupportingFile("infrastructure/ApplicationDelegates.kt.mustache", infrastructureFolder, "ApplicationDelegates.kt")); + supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); + supportingFiles.add(new SupportingFile("infrastructure/ResponseExtensions.kt.mustache", infrastructureFolder, "ResponseExtensions.kt")); + supportingFiles.add(new SupportingFile("infrastructure/ApiInfrastructureResponse.kt.mustache", infrastructureFolder, "ApiInfrastructureResponse.kt")); + } + + private void processMultiplatformLibrary(final String infrastructureFolder) { + commonJvmMultiplatformSupportingFiles(infrastructureFolder); + additionalProperties.put(MULTIPLATFORM, true); + setDateLibrary(DateLibrary.STRING.value); + setRequestDateConverter(RequestDateConverter.TO_STRING.value); + + // multiplatform default includes + defaultIncludes.add("io.ktor.client.request.forms.InputProvider"); + defaultIncludes.add(packageName + ".infrastructure.Base64ByteArray"); + defaultIncludes.add(packageName + ".infrastructure.OctetByteArray"); + + // multiplatform type mapping + typeMapping.put("number", "kotlin.Double"); + typeMapping.put("file", "OctetByteArray"); + typeMapping.put("binary", "OctetByteArray"); + typeMapping.put("ByteArray", "Base64ByteArray"); + typeMapping.put("object", "kotlin.String"); // kotlin.Any not serializable + + // multiplatform import mapping + importMapping.put("BigDecimal", "kotlin.Double"); + importMapping.put("UUID", "kotlin.String"); + importMapping.put("URI", "kotlin.String"); + importMapping.put("InputProvider", "io.ktor.client.request.forms.InputProvider"); + importMapping.put("File", packageName + ".infrastructure.OctetByteArray"); + importMapping.put("Timestamp", "kotlin.String"); + importMapping.put("LocalDateTime", "kotlin.String"); + importMapping.put("LocalDate", "kotlin.String"); + importMapping.put("LocalTime", "kotlin.String"); + importMapping.put("Base64ByteArray", packageName + ".infrastructure.Base64ByteArray"); + importMapping.put("OctetByteArray", packageName + ".infrastructure.OctetByteArray"); + + // multiplatform specific supporting files + supportingFiles.add(new SupportingFile("infrastructure/Base64ByteArray.kt.mustache", infrastructureFolder, "Base64ByteArray.kt")); + supportingFiles.add(new SupportingFile("infrastructure/Bytes.kt.mustache", infrastructureFolder, "Bytes.kt")); + supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt")); + supportingFiles.add(new SupportingFile("infrastructure/OctetByteArray.kt.mustache", infrastructureFolder, "OctetByteArray.kt")); + + // multiplatform specific auth + final String authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/"); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt")); + supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt")); + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt")); + supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt")); + supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt")); + + // multiplatform specific testing files + supportingFiles.add(new SupportingFile("commonTest/Coroutine.kt.mustache", "src/commonTest/kotlin/util", "Coroutine.kt")); + supportingFiles.add(new SupportingFile("iosTest/Coroutine.kt.mustache", "src/iosTest/kotlin/util", "Coroutine.kt")); + supportingFiles.add(new SupportingFile("jsTest/Coroutine.kt.mustache", "src/jsTest/kotlin/util", "Coroutine.kt")); + supportingFiles.add(new SupportingFile("jvmTest/Coroutine.kt.mustache", "src/jvmTest/kotlin/util", "Coroutine.kt")); + + // gradle wrapper supporting files + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.jar")); + } + + + private void commonJvmMultiplatformSupportingFiles(String infrastructureFolder) { + supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); + supportingFiles.add(new SupportingFile("infrastructure/ApiAbstractions.kt.mustache", infrastructureFolder, "ApiAbstractions.kt")); + supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt")); + supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt")); + } + + private void commonSupportingFiles() { + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index 4bd48eb2188..de4b755c2bc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -145,7 +145,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { - this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); } // set default library to "ktor" @@ -185,7 +185,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); } - boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean)additionalProperties.get(CodegenConstants.GENERATE_APIS); + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index a64ffc12eaa..fa884f1bd23 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -639,7 +639,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen @Override public String toModelName(final String name) { // Allow for explicitly configured spring.* - if (name.startsWith("org.springframework.") ) { + if (name.startsWith("org.springframework.")) { return name; } return super.toModelName(name); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java new file mode 100644 index 00000000000..d0985397042 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java @@ -0,0 +1,52 @@ +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MarkdownDocumentationCodegen extends DefaultCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "projectName"; + + static Logger LOGGER = LoggerFactory.getLogger(MarkdownDocumentationCodegen.class); + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "markdown"; + } + + public String getHelp() { + return "Generates a markdown documentation."; + } + + public MarkdownDocumentationCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + outputFolder = "generated-code" + File.separator + "markdown"; + modelTemplateFiles.put("model.mustache", ".md"); + apiTemplateFiles.put("api.mustache", ".md"); + embeddedTemplateDir = templateDir = "markdown-documentation"; + apiPackage = File.separator + "Apis"; + modelPackage = File.separator + "Models"; + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + // TODO: Fill this out. + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java index c286e9e9732..b2b8fd31e76 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java @@ -40,8 +40,8 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { public static final String PSR7_IMPLEMENTATION = "psr7Implementation"; protected String psr7Implementation = "slim-psr7"; - protected List> composerPackages = new ArrayList>(); - protected List> composerDevPackages = new ArrayList>(); + protected String mockDirName = "Mock"; + protected String mockPackage = ""; public PhpSlim4ServerCodegen() { super(); @@ -50,6 +50,7 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { .stability(Stability.STABLE) .build(); + mockPackage = invokerPackage + "\\" + mockDirName; outputFolder = "generated-code" + File.separator + "slim4"; embeddedTemplateDir = templateDir = "php-slim4-server"; @@ -84,6 +85,16 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + // Update the invokerPackage for the default mockPackage + mockPackage = invokerPackage + "\\" + mockDirName; + } + + // make mock src path available in mustache template + additionalProperties.put("mockPackage", mockPackage); + additionalProperties.put("mockSrcPath", "./" + toSrcPath(mockPackage, srcBasePath)); + additionalProperties.put("mockTestPath", "./" + toSrcPath(mockPackage, testBasePath)); + if (additionalProperties.containsKey(PSR7_IMPLEMENTATION)) { this.setPsr7Implementation((String) additionalProperties.get(PSR7_IMPLEMENTATION)); } @@ -116,6 +127,11 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { // Slim 4 doesn't parse JSON body anymore we need to add suggested middleware // ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php")); + + // mocking feature + supportingFiles.add(new SupportingFile("openapi_data_mocker_interface.mustache", toSrcPath(mockPackage, srcBasePath), toInterfaceName("OpenApiDataMocker") + ".php")); + supportingFiles.add(new SupportingFile("openapi_data_mocker.mustache", toSrcPath(mockPackage, srcBasePath), "OpenApiDataMocker.php")); + supportingFiles.add(new SupportingFile("openapi_data_mocker_test.mustache", toSrcPath(mockPackage, testBasePath), "OpenApiDataMockerTest.php")); } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index 16ec0bd3c03..4538ee1b5f2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -273,7 +273,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } - private static String dropDots(String str) { + protected static String dropDots(String str) { return str.replaceAll("\\.", "_"); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java index 13cbb443aab..eb3c65438ea 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java @@ -52,6 +52,8 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { // this may set datatype right for additional properties instantiationTypes.put("map", "dict"); + languageSpecificPrimitives.add("file_type"); + languageSpecificPrimitives.add("none_type"); apiTemplateFiles.remove("api.mustache"); apiTemplateFiles.put("python-experimental/api.mustache", ".py"); @@ -65,6 +67,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { modelTemplateFiles.remove("model.mustache"); modelTemplateFiles.put("python-experimental/model.mustache", ".py"); + modelTestTemplateFiles.remove("model_test.mustache", ".py"); + modelTestTemplateFiles.put("python-experimental/model_test.mustache", ".py"); + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.EXPERIMENTAL) .build(); @@ -79,11 +84,33 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { supportingFiles.add(new SupportingFile("python-experimental/model_utils.mustache", packagePath(), "model_utils.py")); + supportingFiles.remove(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + "models", "__init__.py")); + supportingFiles.add(new SupportingFile("python-experimental/__init__model.mustache", packagePath() + File.separatorChar + "models", "__init__.py")); + + supportingFiles.remove(new SupportingFile("__init__package.mustache", packagePath(), "__init__.py")); + supportingFiles.add(new SupportingFile("python-experimental/__init__package.mustache", packagePath(), "__init__.py")); + + Boolean generateSourceCodeOnly = false; if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) { generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString()); } + // remove what PythonClientCodegen did + String readmePath = "README.md"; + String readmeTemplate = "README.mustache"; + if (generateSourceCodeOnly) { + readmePath = packagePath() + "_" + readmePath; + readmeTemplate = "README_onlypackage.mustache"; + } + supportingFiles.remove(new SupportingFile(readmeTemplate, "", readmePath)); + // add the correct readme + readmeTemplate = "python-experimental/README.mustache"; + if (generateSourceCodeOnly) { + readmeTemplate = "python-experimental/README_onlypackage.mustache"; + } + supportingFiles.add(new SupportingFile(readmeTemplate, "", readmePath)); + if (!generateSourceCodeOnly) { supportingFiles.remove(new SupportingFile("setup.mustache", "", "setup.py")); supportingFiles.add(new SupportingFile("python-experimental/setup.mustache", "", "setup.py")); @@ -213,19 +240,76 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { } } - public void addModelImport(Map objs, CodegenModel cm, String otherModelName) { - // adds the absolute path to otherModelName as an import in CodegenModel cm - HashMap referencedModel = (HashMap) objs.get(otherModelName); - if (referencedModel == null) { - // this happens with a model where type=string and format=number which is a non-standard format + @Override + public String toModelImport(String name) { + // name looks like cat.Cat + String moduleName = name.split("\\.")[0]; + // https://exceptionshub.com/circular-or-cyclic-imports-in-python.html + return "from " + modelPackage() + " import "+ moduleName; + } + + private String robustImport(String name) { + // name looks like cat.Cat + String moduleName = name.split("\\.")[0]; + // https://exceptionshub.com/circular-or-cyclic-imports-in-python.html + String modelImport = "try:\n from " + modelPackage() + " import "+ moduleName+ "\nexcept ImportError:\n "+moduleName+" = sys.modules['"+modelPackage() + "."+ moduleName+"']"; + return modelImport; + } + + private String getPythonClassName(String name) { + // name looks like cat.Cat or Cat + String[] pieces = name.split("\\."); + if (pieces.length == 1) { + return pieces[0]; + } + return pieces[1]; + } + + private void fixOperationImports(Set imports) { + if (imports.size() == 0) { return; } - ArrayList myModel = (ArrayList) referencedModel.get("models"); - HashMap modelData = (HashMap) myModel.get(0); - String importPath = (String) modelData.get("importPath"); - // only add importPath to parameters if it isn't in importPaths - if (!cm.imports.contains(importPath)) { - cm.imports.add(importPath); + String[] modelNames = imports.toArray(new String[0]); + imports.clear(); + // loops through imports and converts them all from 'module.Class' to 'from models.module import module' + for (String modelName : modelNames) { + // if a modelName lacks the module (Pet) then we convert it to pet.Pet + if (modelName.indexOf(".") == -1) { + modelName = toModelName(modelName); + } + imports.add(toModelImport(modelName)); + } + } + + @Override + @SuppressWarnings("static-method") + public Map postProcessOperationsWithModels(Map objs, List allModels) { + HashMap val = (HashMap)objs.get("operations"); + ArrayList operations = (ArrayList) val.get("operation"); + ArrayList> imports = (ArrayList>)objs.get("imports"); + imports.clear(); + for (CodegenOperation operation : operations) { + fixOperationImports(operation.imports); + for (String thisImport : operation.imports) { + HashMap higherImport = new HashMap(); + higherImport.put("import", thisImport); + if (!imports.contains(higherImport)) { + imports.add(higherImport); + } + } + } + return objs; + } + + private void fixModelImports(Set imports) { + // loops through imports and converts them all from 'module.Class' to 'import models.module as module' + if (imports.size() == 0) { + return; + } + String[] modelNames = imports.toArray(new String[0]); + imports.clear(); + for (String modelName : modelNames) { + imports.add(robustImport(modelName)); } } @@ -241,40 +325,30 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { for (Map mo : models) { CodegenModel cm = (CodegenModel) mo.get("model"); - // fix the imports that each model has, change them to absolute - // imports - // clear out imports so we will only include full path imports - cm.imports.clear(); + // make sure discrimonator models are included in imports CodegenDiscriminator discriminator = cm.discriminator; if (discriminator != null) { Set mappedModels = discriminator.getMappedModels(); for (CodegenDiscriminator.MappedModel mappedModel : mappedModels) { String otherModelName = mappedModel.getModelName(); - addModelImport(objs, cm, otherModelName); + cm.imports.add(otherModelName); } } - ArrayList> listOfLists= new ArrayList>(); - listOfLists.add(cm.allVars); - listOfLists.add(cm.requiredVars); - listOfLists.add(cm.optionalVars); - listOfLists.add(cm.vars); - for (List varList : listOfLists) { - for (CodegenProperty cp : varList) { - String otherModelName = null; - if (cp.complexType != null) { - otherModelName = cp.complexType; - } - if (cp.mostInnerItems != null) { - if (cp.mostInnerItems.complexType != null) { - otherModelName = cp.mostInnerItems.complexType; - } - } - if (otherModelName != null) { - addModelImport(objs, cm, otherModelName); - } - } + + // add imports for anyOf, allOf, oneOf + ArrayList> composedSchemaSets = new ArrayList>(); + composedSchemaSets.add(cm.allOf); + composedSchemaSets.add(cm.anyOf); + composedSchemaSets.add(cm.oneOf); + for (Set importSet : composedSchemaSets) { + for (String otherModelName : importSet) { + cm.imports.add(otherModelName); + } } + // fix the imports that each model has, change them to absolute + fixModelImports(cm.imports); + Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name); CodegenProperty modelProperty = fromProperty("value", modelSchema); if (cm.isEnum || cm.isAlias) { @@ -396,17 +470,20 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { CodegenProperty modelProp = fromProperty("body", realSchema); if (modelProp.isPrimitiveType && (modelProp.hasValidation || modelProp.isEnum)) { String simpleDataType = result.dataType; - result.isPrimitiveType = false; - result.isModel = true; - result.dataType = modelName; - imports.add(modelName); + result.dataType = toModelName(modelName); + result.baseType = getPythonClassName(result.dataType); + imports.remove(modelName); + imports.add(result.dataType); // set the example value if (modelProp.isEnum) { String value = modelProp._enum.get(0).toString(); - result.example = modelName + "(" + toEnumValue(value, simpleDataType) + ")"; + result.example = this.packageName + "." + result.baseType + "(" + toEnumValue(value, simpleDataType) + ")"; } else { - result.example = modelName + "(" + result.example + ")"; + result.example = this.packageName + "." + result.baseType + "(" + result.example + ")"; } + } else if (!result.isPrimitiveType) { + // fix the baseType for the api docs so the .md link to the class's documentation file is correct + result.baseType = getPythonClassName(result.baseType); } return result; } @@ -421,7 +498,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { @Override public CodegenResponse fromResponse(String responseCode, ApiResponse response) { // if a response points at a model whose type != object and it has validations and/or enums, then we will - // generate the model, and the response.isModel must be changed to true and response.baseType must be the name + // generate the model, and response.baseType must be the name // of the model. Point responses at models if the model is python class type ModelSimple // When we serialize/deserialize ModelSimple models, validations and enums will be checked. Schema responseSchema; @@ -435,13 +512,13 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { if (responseSchema != null) { CodegenProperty cp = fromProperty("response", responseSchema); if (cp.complexType != null) { - // check the referenced schema to see if it is an type=object model - Schema modelSchema = ModelUtils.getSchema(this.openAPI, cp.complexType); + String modelName = getPythonClassName(cp.complexType); + Schema modelSchema = ModelUtils.getSchema(this.openAPI, modelName); if (modelSchema != null && !"object".equals(modelSchema.getType())) { CodegenProperty modelProp = fromProperty("response", modelSchema); if (modelProp.isEnum == true || modelProp.hasValidation == true) { // this model has validations and/or enums so we will generate it - newBaseType = cp.complexType; + newBaseType = modelName; } } } else { @@ -455,9 +532,12 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { CodegenResponse result = super.fromResponse(responseCode, response); if (newBaseType != null) { - result.isModel = true; - result.baseType = newBaseType; - result.dataType = newBaseType; + result.dataType = toModelName(newBaseType); + // baseType is used to set the link to the model .md documentation + result.baseType = getPythonClassName(newBaseType); + } else if (!result.primitiveType) { + // fix the baseType for the api docs so the .md link to the class's documentation file is correct + result.baseType = getPythonClassName(result.baseType); } return result; @@ -553,6 +633,31 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { } } + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty p) { + postProcessPattern(p.pattern, p.vendorExtensions); + // set property.complexType so the model docs will link to the ClassName.md + if (p.complexType != null && !languageSpecificPrimitives.contains(p.complexType)) { + p.complexType = getPythonClassName(p.complexType); + } else if (p.isListContainer && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) { + // fix ListContainers + p.complexType = getPythonClassName(p.mostInnerItems.complexType); + } + } + + @Override + public void postProcessParameter(CodegenParameter p) { + postProcessPattern(p.pattern, p.vendorExtensions); + // set baseType to null so the api docs will not point to a model for languageSpecificPrimitives + if (p.baseType != null && languageSpecificPrimitives.contains(p.baseType)){ + p.baseType = null; + } else if (p.isListContainer && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) { + // fix ListContainers + p.baseType = getPythonClassName(p.mostInnerItems.complexType); + } + } + + /** * Convert OAS Model object to Codegen Model object * @@ -588,10 +693,15 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { continue; } String modelName = ModelUtils.getSimpleRef(ref); - propertyToModelName.put(pythonPropertyName, modelName); + propertyToModelName.put(pythonPropertyName, toModelName(modelName)); } } CodegenModel result = super.fromModel(name, schema); + // use this to store the model name like Cat + // we can't use result.name because that is used to lookup models in the spec + // we can't use result.classname because that stores cat.Cat + // we can't use result.classVarName because that stores the variable for making example instances + result.unescapedDescription = simpleModelName(name); // make non-object type models have one property so we can use it to store enums and validations if (result.isAlias || result.isEnum) { @@ -636,10 +746,11 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { } cp.isPrimitiveType = false; String modelName = propertyToModelName.get(cp.name); - cp.complexType = modelName; + cp.complexType = getPythonClassName(modelName); cp.dataType = modelName; cp.isEnum = false; cp.hasValidation = false; + result.imports.add(modelName); } } return result; @@ -671,7 +782,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { if (ModelUtils.isFreeFormObject(p) && ModelUtils.getAdditionalProperties(p) == null) { return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix; } - if (ModelUtils.isMapSchema(p)) { + if ((ModelUtils.isMapSchema(p) || p.getType() == "object") && ModelUtils.getAdditionalProperties(p) != null) { Schema inner = ModelUtils.getAdditionalProperties(p); return prefix + "{str: " + getTypeString(inner, "(", ")") + "}" + fullSuffix; } else if (ModelUtils.isArraySchema(p)) { @@ -679,10 +790,10 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { Schema inner = ap.getItems(); return prefix + "[" + getTypeString(inner, "", "") + "]" + fullSuffix; } - String baseType = getSimpleTypeDeclaration(p); if (ModelUtils.isFileSchema(p)) { - baseType = "file_type"; + return prefix + "file_type" + fullSuffix; } + String baseType = getSimpleTypeDeclaration(p); return prefix + baseType + fullSuffix; } @@ -772,8 +883,8 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { } example = "'" + escapeText(example) + "'"; } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - example = this.packageName + "." + type + "()"; + // type is a model class, e.g. user.User + example = this.packageName + "." + getPythonClassName(type) + "()"; } else { LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); } @@ -788,4 +899,55 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { p.example = example; } + + private String simpleModelName(String name) { + // this returns a model name like Cat + String modelName = sanitizeName(name); + // remove dollar sign + modelName = modelName.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(modelName)) { + LOGGER.warn(modelName + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + modelName)); + modelName = "model_" + modelName; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (modelName.matches("^\\d.*")) { + LOGGER.warn(modelName + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + modelName)); + modelName = "model_" + modelName; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + modelName = modelNamePrefix + "_" + modelName; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + modelName = modelName + "_" + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(modelName); + } + + + @Override + public String toModelFilename(String name) { + // underscore the model file name + // PhoneNumber => phone_number + return underscore(dropDots(simpleModelName(name))); + } + + @Override + public String toModelName(String name) { + // we have a custom version of this function so we can support circular references in python 2 and 3 + return toModelFilename(name)+"."+simpleModelName(name); + } + + @Override + public String toModelDocFilename(String name) { + // this is used to generate the model's .md documentation file + return simpleModelName(name); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java index 03d7ed690bf..54b85882575 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java @@ -213,6 +213,8 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(CodegenConstants.NON_PUBLIC_API, CodegenConstants.NON_PUBLIC_API_DESC + "(default: false)")); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + "(which would crash the app if api returns null as opposed " diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java index 30f924fda4c..3976629470b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java @@ -144,6 +144,22 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege return objs; } + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map model : models) { + CodegenModel codegenModel = (CodegenModel) model.get("model"); + model.put("hasAllOf", codegenModel.allOf.size() > 0); + model.put("hasOneOf", codegenModel.oneOf.size() > 0); + } + } + return result; + } + + @Override protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { codegenModel.additionalPropertiesType = getTypeDeclaration(ModelUtils.getAdditionalProperties(schema)); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index 780857f606c..ad53e421ef5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -29,10 +29,12 @@ import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.IJsonSchemaValidationProperties; import org.openapitools.codegen.config.GlobalSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -1003,4 +1005,33 @@ public class ModelUtils { return false; } + + public static void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target){ + if (schema != null && target != null) { + target.setPattern(schema.getPattern()); + BigDecimal minimum = schema.getMinimum(); + BigDecimal maximum = schema.getMaximum(); + Boolean exclusiveMinimum = schema.getExclusiveMinimum(); + Boolean exclusiveMaximum = schema.getExclusiveMaximum(); + Integer minLength = schema.getMinLength(); + Integer maxLength = schema.getMaxLength(); + Integer minItems = schema.getMinItems(); + Integer maxItems = schema.getMaxItems(); + Boolean uniqueItems = schema.getUniqueItems(); + Integer minProperties = schema.getMinProperties(); + Integer maxProperties = schema.getMaxProperties(); + + if (minimum != null) target.setMinimum(String.valueOf(minimum)); + if (maximum != null) target.setMaximum(String.valueOf(maximum)); + if (exclusiveMinimum != null) target.setExclusiveMinimum(exclusiveMinimum); + if (exclusiveMaximum != null) target.setExclusiveMaximum(exclusiveMaximum); + if (minLength != null) target.setMinLength(minLength); + if (maxLength != null) target.setMaxLength(maxLength); + if (minItems != null) target.setMinItems(minItems); + if (maxItems != null) target.setMaxItems(maxItems); + if (uniqueItems != null) target.setUniqueItems(uniqueItems); + if (minProperties != null) target.setMinProperties(minProperties); + if (maxProperties != null) target.setMaxProperties(maxProperties); + } + } } diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index 2ef5d0eeec1..56c719f1e08 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -141,7 +141,7 @@ list_addElement(localVarQueryParameters,{{paramName}}); {{/isListContainer}} {{^isListContainer}} - keyQuery_{{{paramName}}} = strdup("{{{paramName}}}"); + keyQuery_{{{paramName}}} = strdup("{{{baseName}}}"); valueQuery_{{{paramName}}} = {{#isString}}{{^isEnum}}strdup({{/isEnum}}{{/isString}}({{{paramName}}}){{#isString}}{{^isEnum}}){{/isEnum}}{{/isString}}; keyPairQuery_{{paramName}} = keyValuePair_create(keyQuery_{{{paramName}}}, {{#isEnum}}(void *){{/isEnum}}{{^isString}}&{{/isString}}valueQuery_{{{paramName}}}); list_addElement(localVarQueryParameters,keyPairQuery_{{paramName}}); diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache index 527c1b24350..3c133c12dc2 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache @@ -633,31 +633,31 @@ fail: {{/isPrimitiveType}} {{/isListContainer}} {{#isMapContainer}} - list_t *{{{complexType}}}List; + list_t *{{{name}}}List; {{^required}}if ({{{name}}}) { {{/required}} - cJSON *{{{complexType}}}_local_map; + cJSON *{{{name}}}_local_map; if(!cJSON_IsObject({{{name}}})) { goto end;//primitive map container } - {{{complexType}}}List = list_create(); + {{{name}}}List = list_create(); keyValuePair_t *localMapKeyPair; - cJSON_ArrayForEach({{{complexType}}}_local_map, {{{name}}}) + cJSON_ArrayForEach({{{name}}}_local_map, {{{name}}}) { {{#isString}} - if(!cJSON_IsString({{{complexType}}}_local_map)) + if(!cJSON_IsString({{{name}}}_local_map)) { goto end; } - localMapKeyPair = keyValuePair_create(strdup({{{complexType}}}_local_map->string),strdup({{{complexType}}}_local_map->valuestring)) - list_addElement({{{complexType}}}List , localMapKeyPair); + localMapKeyPair = keyValuePair_create(strdup({{{name}}}_local_map->string),strdup({{{name}}}_local_map->valuestring)) + list_addElement({{{name}}}List , localMapKeyPair); {{/isString}} {{^isString}} - if(!cJSON_IsNumber({{{complexType}}}_local_map)) + if(!cJSON_IsNumber({{{name}}}_local_map)) { goto end; } - localMapKeyPair = keyValuePair_create(strdup({{{complexType}}}_local_map->string),&{{{complexType}}}_local_map->valuedouble ); - list_addElement({{{complexType}}}List , localMapKeyPair); + localMapKeyPair = keyValuePair_create(strdup({{{name}}}_local_map->string),&{{{name}}}_local_map->valuedouble ); + list_addElement({{{name}}}List , localMapKeyPair); {{/isString}} } {{/isMapContainer}} @@ -731,7 +731,7 @@ fail: {{/isPrimitiveType}} {{/isListContainer}} {{#isMapContainer}} - {{^required}}{{{name}}} ? {{/required}}{{{complexType}}}List{{^required}} : NULL{{/required}}{{#hasMore}},{{/hasMore}} + {{^required}}{{{name}}} ? {{/required}}{{{name}}}List{{^required}} : NULL{{/required}}{{#hasMore}},{{/hasMore}} {{/isMapContainer}} {{/isContainer}} {{/vars}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache index 10fd280281c..4694c0980f2 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache @@ -11,8 +11,10 @@ minLength not set, maxLength set }}{{#minItems}}{{^maxItems}}@Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{! @Size: minItems not set && maxItems set }}{{^minItems}}{{#maxItems}}@Size(max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! -@Email: performBeanValidation set && isEmail set -}}{{#performBeanValidation}}{{#isEmail}}@Email{{/isEmail}}{{/performBeanValidation}}{{! +@Email: useBeanValidation set && isEmail && java8 set +}}{{#useBeanValidation}}{{#isEmail}}{{#java8}}@javax.validation.constraints.Email{{/java8}}{{/isEmail}}{{/useBeanValidation}}{{! +@Email: performBeanValidation set && isEmail && not java8 set +}}{{#performBeanValidation}}{{#isEmail}}{{^java8}}@org.hibernate.validator.constraints.Email{{/java8}}{{/isEmail}}{{/performBeanValidation}}{{! check for integer or long / all others=decimal type with @Decimal* isInteger set }}{{#isInteger}}{{#minimum}}@Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}) {{/maximum}}{{/isInteger}}{{! diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache index 16ac260f9d9..c2a1faa8c9f 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue={{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody {{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isListContainer}}Mono{{/isListContainer}}{{#isListContainer}}Flux{{/isListContainer}}<{{{baseType}}}>{{/reactive}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue={{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody{{^required}}(required = false){{/required}} {{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isListContainer}}Mono{{/isListContainer}}{{#isListContainer}}Flux{{/isListContainer}}<{{{baseType}}}>{{/reactive}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 0c9ee852110..6876bd98995 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -122,3 +122,5 @@ org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen org.openapitools.codegen.languages.FsharpGiraffeServerCodegen org.openapitools.codegen.languages.AsciidocDocumentationCodegen org.openapitools.codegen.languages.FsharpFunctionsServerCodegen + +org.openapitools.codegen.languages.MarkdownDocumentationCodegen diff --git a/modules/openapi-generator/src/main/resources/dart-dio/enum.mustache b/modules/openapi-generator/src/main/resources/dart-dio/enum.mustache index ace44b16e0d..3f6af81d620 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/enum.mustache @@ -11,12 +11,11 @@ class {{classname}} extends EnumClass { {{#description}} /// {{description}} {{/description}} - @BuiltValueEnumConst(wireName: '{{name}}') + @BuiltValueEnumConst(wireName: {{{value}}}) static const {{classname}} {{name}} = _${{name}}; {{/enumVars}} {{/allowableValues}} - static Serializer<{{classname}}> get serializer => _${{classVarName}}Serializer; const {{classname}}._(String name): super(name); diff --git a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache index 7c280441649..8092a49d515 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache @@ -1,6 +1,7 @@ -# See https://www.dartlang.org/tools/private-files.html +# See https://dart.dev/guides/libraries/private-files # Files and directories created by pub +.dart_tool/ .buildlog .packages .project @@ -25,3 +26,12 @@ doc/api/ # Don't commit pubspec lock file # (Library packages only! Remove pattern if developing an application package) pubspec.lock + +# Don’t commit files and directories created by other development environments. +# For example, if your development environment creates any of the following files, +# consider putting them in a global ignore file: +*.iml // IntelliJ +*.ipr // IntelliJ +*.iws // IntelliJ +.idea/ // IntelliJ +.DS_Store // Mac diff --git a/modules/openapi-generator/src/main/resources/dart-dio/local_date_serializer.mustache b/modules/openapi-generator/src/main/resources/dart-dio/local_date_serializer.mustache new file mode 100644 index 00000000000..2fb73ef0aae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart-dio/local_date_serializer.mustache @@ -0,0 +1,23 @@ +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:time_machine/time_machine.dart'; + +class LocalDateSerializer implements PrimitiveSerializer { + @override + Iterable get types => BuiltList([LocalDate]); + + @override + String get wireName => "LocalDate"; + + @override + LocalDate deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + return LocalDate.dateTime(DateTime.parse(serialized as String)); + } + + @override + Object serialize(Serializers serializers, LocalDate localDate, + {FullType specifiedType = FullType.unspecified}) { + return localDate.toString('yyyy-MM-dd'); + } +} diff --git a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache index 0cfa432854b..90b1b532962 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache @@ -7,7 +7,10 @@ dependencies: dio: ^3.0.4 built_value: ^6.8.2 built_collection: ^4.2.2 +{{#timeMachine}} + time_machine: ^0.9.12 +{{/timeMachine}} dev_dependencies: built_value_generator: ^6.8.2 build_runner: ^1.7.1 - test: 1.6.5 \ No newline at end of file + test: 1.6.5 diff --git a/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache b/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache index dea3a0ecff1..2d850a28c90 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/serializers.mustache @@ -4,7 +4,7 @@ import 'package:built_value/serializer.dart'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/standard_json_plugin.dart'; - +{{#timeMachine}}import 'package:{{pubName}}/local_date_serializer.dart';{{/timeMachine}} {{#models}}{{#model}}import 'package:{{pubName}}/model/{{classFilename}}.dart'; {{/model}}{{/models}} @@ -24,4 +24,5 @@ const FullType(BuiltList, const [const FullType({{classname}})]), ).build(); Serializers standardSerializers = -(serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); +(serializers.toBuilder() +{{#timeMachine}}..add(LocalDateSerializer()){{/timeMachine}}..addPlugin(StandardJsonPlugin())).build(); diff --git a/modules/openapi-generator/src/main/resources/go-experimental/README.mustache b/modules/openapi-generator/src/main/resources/go-experimental/README.mustache index 2f51e5cbccf..cdb72d59099 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/README.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/README.mustache @@ -34,6 +34,47 @@ Put the package under your project folder and add the following in import: import sw "./{{packageName}}" ``` +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + ## Documentation for API Endpoints All URIs are relative to *{{basePath}}* diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache index 067704ec555..507fdcfc0ce 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache @@ -76,10 +76,13 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams {{/returnType}} ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}} - localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.QueryEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1) - {{/pathParams}} + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "{{{classname}}}Service.{{{nickname}}}") + if err != nil { + return {{#returnType}}localVarReturnValue, {{/returnType}}nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "{{{path}}}"{{#pathParams}} + localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.QueryEscape(parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")) , -1){{/pathParams}} localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -332,7 +335,6 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams newErr.model = v {{#hasMore}} return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr - return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr {{/hasMore}} {{^wildcard}} } diff --git a/modules/openapi-generator/src/main/resources/go-experimental/client.mustache b/modules/openapi-generator/src/main/resources/go-experimental/client.mustache index 6b26a31bea2..6678caedfb8 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/client.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/client.mustache @@ -186,11 +186,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return resp, err } -// ChangeBasePath changes base path to allow switching to mocks -func (c *APIClient) ChangeBasePath(path string) { - c.cfg.BasePath = path -} - // Allow modification of underlying config for alternate implementations and testing // Caution: modifying the configuration while live can cause data races and potentially unwanted behavior func (c *APIClient) GetConfig() *Configuration { diff --git a/modules/openapi-generator/src/main/resources/go-experimental/configuration.mustache b/modules/openapi-generator/src/main/resources/go-experimental/configuration.mustache index 9d52ea1f528..28f235e694b 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/configuration.mustache @@ -2,6 +2,7 @@ package {{packageName}} import ( + "context" "fmt" "net/http" "strings" @@ -29,6 +30,18 @@ var ( // ContextAPIKeys takes a string apikey as authentication for the request ContextAPIKeys = contextKey("apiKeys") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth @@ -52,35 +65,38 @@ type ServerVariable struct { // ServerConfiguration stores the information about a server type ServerConfiguration struct { - Url string + URL string Description string Variables map[string]ServerVariable } +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + // Configuration stores the configuration of the API client type Configuration struct { - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - Debug bool `json:"debug,omitempty"` - Servers []ServerConfiguration - HTTPClient *http.Client + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client } // NewConfiguration returns a new Configuration object func NewConfiguration() *Configuration { cfg := &Configuration{ - BasePath: "{{{basePath}}}", - DefaultHeader: make(map[string]string), - UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}", - Debug: false, + DefaultHeader: make(map[string]string), + UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}", + Debug: false, {{#servers}} {{#-first}} - Servers: []ServerConfiguration{{ + Servers: ServerConfigurations{ {{/-first}} - Url: "{{{url}}}", + { + URL: "{{{url}}}", Description: "{{{description}}}{{^description}}No description provided{{/description}}", {{#variables}} {{#-first}} @@ -108,6 +124,49 @@ func NewConfiguration() *Configuration { }, {{/-last}} {{/servers}} + {{#apiInfo}} + OperationServers: map[string]ServerConfigurations{ + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + "{{{classname}}}Service.{{{nickname}}}": { + {{/-first}} + { + URL: "{{{url}}}", + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + Variables: map[string]ServerVariable{ + {{/-first}} + "{{{name}}}": ServerVariable{ + Description: "{{{description}}}{{^description}}No description provided{{/description}}", + DefaultValue: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + EnumValues: []string{ + {{/-first}} + "{{{.}}}", + {{#-last}} + }, + {{/-last}} + {{/enumValues}} + }, + {{#-last}} + }, + {{/-last}} + {{/variables}} + }, + {{#-last}} + }, + {{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + }, + {{/apiInfo}} } return cfg } @@ -117,13 +176,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } -// ServerUrl returns URL based on server settings -func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) { - if index < 0 || len(c.Servers) <= index { - return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1) +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) } - server := c.Servers[index] - url := server.Url + server := sc[index] + url := server.URL // go through variables and replace placeholders for name, variable := range server.Variables { @@ -144,3 +203,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin } return url, nil } + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/modules/openapi-generator/src/main/resources/go-experimental/model.mustache b/modules/openapi-generator/src/main/resources/go-experimental/model.mustache index c72fab46a94..cbffd1fc340 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/model.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/model.mustache @@ -25,32 +25,6 @@ const ( {{/enumVars}} {{/allowableValues}} ) - -type Nullable{{{classname}}} struct { - Value {{{classname}}} - ExplicitNull bool -} - -func (v Nullable{{{classname}}}) MarshalJSON() ([]byte, error) { - switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable - case v.ExplicitNull: - return []byte("null"), nil - default: - return json.Marshal(v.Value) - } -} - -func (v *Nullable{{{classname}}}) UnmarshalJSON(src []byte) error { - if bytes.Equal(src, []byte("null")) { - v.ExplicitNull = true - return nil - } - - return json.Unmarshal(src, &v.Value) -} - {{/isEnum}} {{^isEnum}} // {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}} @@ -121,6 +95,7 @@ func (o *{{classname}}) Set{{name}}(v {{dataType}}) { {{/required}} {{/vars}} +{{/isEnum}} type Nullable{{{classname}}} struct { Value {{{classname}}} ExplicitNull bool @@ -132,7 +107,7 @@ func (v Nullable{{{classname}}}) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *Nullable{{{classname}}}) UnmarshalJSON(src []byte) error { @@ -143,7 +118,5 @@ func (v *Nullable{{{classname}}}) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } -{{/isEnum}} - {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/api.mustache index b7d8532a2fd..7d7cec63425 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/api.mustache @@ -39,17 +39,17 @@ import {{packageName}}.infrastructure.toMultiValue {{#queryParams}} {{^required}} if ({{paramName}} != null) { - put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{paramName}}.toString()){{/isContainer}}) + put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{paramName}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{paramName}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{paramName}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) } {{/required}} {{#required}} {{#isNullable}} if ({{paramName}} != null) { - put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{paramName}}.toString()){{/isContainer}}) + put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{paramName}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{paramName}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{paramName}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) } {{/isNullable}} {{^isNullable}} - put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{paramName}}.toString()){{/isContainer}}) + put("{{paramName}}", {{#isContainer}}toMultiValue({{paramName}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{paramName}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{paramName}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{paramName}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) {{/isNullable}} {{/required}} {{/queryParams}} @@ -71,8 +71,14 @@ import {{packageName}}.infrastructure.toMultiValue ResponseType.Success -> {{#returnType}}(localVarResponse as Success<*>).data as {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache index 32d352d2717..bcb48ed060a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache @@ -7,7 +7,10 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' + {{#jvm-retrofit2}} + ext.retrofitVersion = '2.6.2' + {{/jvm-retrofit2}} repositories { mavenCentral() @@ -18,6 +21,9 @@ buildscript { } apply plugin: 'kotlin' +{{#moshiCodeGen}} +apply plugin: 'kotlin-kapt' +{{/moshiCodeGen}} repositories { mavenCentral() @@ -31,8 +37,14 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" {{#moshi}} - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + {{^moshiCodeGen}} + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + {{/moshiCodeGen}} + compile "com.squareup.moshi:moshi-adapters:1.9.2" + {{#moshiCodeGen}} + compile "com.squareup.moshi:moshi:1.9.2" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" + {{/moshiCodeGen}} {{/moshi}} {{#gson}} compile "com.google.code.gson:gson:2.8.6" @@ -46,5 +58,15 @@ dependencies { {{#threetenbp}} compile "org.threeten:threetenbp:1.4.0" {{/threetenbp}} + {{#jvm-retrofit2}} + compile "com.squareup.retrofit2:retrofit:$retrofitVersion" + {{#gson}} + compile "com.squareup.retrofit2:converter-gson:$retrofitVersion" + {{/gson}} + {{#moshi}} + compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + {{/moshi}} + compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + {{/jvm-retrofit2}} testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index d3fc818aaa7..47d2d5e9d28 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -1,16 +1,19 @@ -{{#jvm}} +{{^multiplatform}} {{#gson}} import com.google.gson.annotations.SerializedName {{/gson}} {{#moshi}} import com.squareup.moshi.Json +{{#moshiCodeGen}} +import com.squareup.moshi.JsonClass +{{/moshiCodeGen}} {{/moshi}} {{#parcelizeModels}} import android.os.Parcelable import kotlinx.android.parcel.Parcelize {{/parcelizeModels}} -{{/jvm}} +{{/multiplatform}} {{#multiplatform}} import kotlinx.serialization.* import kotlinx.serialization.internal.CommonEnumSerializer @@ -27,13 +30,11 @@ import java.io.Serializable {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -{{#multiplatform}}@Serializable{{/multiplatform}} +{{#multiplatform}}@Serializable{{/multiplatform}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}} {{#nonPublicApi}}internal {{/nonPublicApi}}data class {{classname}} ( -{{#requiredVars}} -{{>data_class_req_var}}{{^-last}}, -{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, -{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>data_class_opt_var}}{{^-last}}, -{{/-last}}{{/optionalVars}} +{{#vars}} +{{#required}}{{>data_class_req_var}}{{/required}}{{^required}}{{>data_class_opt_var}}{{/required}}{{^-last}},{{/-last}} +{{/vars}} ) {{^serializableModel}}{{#parcelizeModels}} : Parcelable{{/parcelizeModels}}{{/serializableModel}} {{^parcelizeModels}}{{#serializableModel}}: Serializable {{/serializableModel}}{{/parcelizeModels}} {{#parcelizeModels}}{{#serializableModel}} : Parcelable, Serializable {{/serializableModel}}{{/parcelizeModels}} @@ -56,14 +57,14 @@ import java.io.Serializable {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{{nameInCamelCase}}}(val value: {{#isListContainer}}{{{ nestedType }}}{{/isListContainer}}{{^isListContainer}}{{{dataType}}}{{/isListContainer}}){ {{#allowableValues}} {{#enumVars}} - {{#jvm}} + {{^multiplatform}} {{#moshi}} @Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/moshi}} {{#gson}} @SerializedName(value={{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/gson}} - {{/jvm}} + {{/multiplatform}} {{#multiplatform}} {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/multiplatform}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache index ff0fc3a4ce5..3a8d2871db6 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache @@ -1,12 +1,12 @@ {{#description}} /* {{{description}}} */ {{/description}} - {{#jvm}} + {{^multiplatform}} {{#moshi}} @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") {{/moshi}} {{#gson}} @SerializedName("{{{vendorExtensions.x-base-name-literal}}}") {{/gson}} - {{/jvm}} + {{/multiplatform}} {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isListContainer}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{classname}}.{{{nameInCamelCase}}}>{{/isListContainer}}{{^isListContainer}}{{classname}}.{{{nameInCamelCase}}}{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache index c7a068e7ca3..ca645e26c85 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache @@ -1,12 +1,12 @@ {{#description}} /* {{{description}}} */ {{/description}} - {{#jvm}} + {{^multiplatform}} {{#moshi}} @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") {{/moshi}} {{#gson}} @SerializedName("{{{vendorExtensions.x-base-name-literal}}}") {{/gson}} - {{/jvm}} + {{/multiplatform}} {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isListContainer}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{classname}}.{{{nameInCamelCase}}}>{{/isListContainer}}{{^isListContainer}}{{classname}}.{{{nameInCamelCase}}}{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 9c848451846..73113186c51 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -1,11 +1,11 @@ -{{#jvm}} +{{^multiplatform}} {{#gson}} import com.google.gson.annotations.SerializedName {{/gson}} {{#moshi}} import com.squareup.moshi.Json {{/moshi}} -{{/jvm}} +{{/multiplatform}} {{#multiplatform}} import kotlinx.serialization.* import kotlinx.serialization.internal.CommonEnumSerializer @@ -19,14 +19,14 @@ import kotlinx.serialization.internal.CommonEnumSerializer {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}){ {{#allowableValues}}{{#enumVars}} - {{#jvm}} + {{^multiplatform}} {{#moshi}} @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{/moshi}} {{#gson}} @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{/gson}} - {{/jvm}} + {{/multiplatform}} {{#isListContainer}} {{#isList}} {{&name}}(listOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ByteArrayAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/ByteArrayAdapter.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ByteArrayAdapter.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/ByteArrayAdapter.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/DateAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/DateAdapter.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/DateAdapter.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/DateAdapter.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/LocalDateAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/LocalDateAdapter.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/LocalDateTimeAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/LocalDateTimeAdapter.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Serializer.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache similarity index 77% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Serializer.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache index df4c33c26d2..201db4b9d56 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Serializer.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache @@ -3,7 +3,9 @@ package {{packageName}}.infrastructure {{#moshi}} import com.squareup.moshi.Moshi import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter +{{^moshiCodeGen}} import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +{{/moshiCodeGen}} {{/moshi}} {{#gson}} import com.google.gson.Gson @@ -23,23 +25,32 @@ import java.util.Date {{#nonPublicApi}}internal {{/nonPublicApi}}object Serializer { {{#moshi}} @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + {{^moshiCodeGen}} .add(KotlinJsonAdapterFactory()) - .build() + {{/moshiCodeGen}} + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } {{/moshi}} {{#gson}} @JvmStatic - val gson: Gson = GsonBuilder() + val gsonBuilder: GsonBuilder = GsonBuilder() .registerTypeAdapter(Date::class.java, DateAdapter()) .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) - .registerTypeAdapter(UUID::class.java, UUIDAdapter()) .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) - .create() + + @JvmStatic + val gson: Gson by lazy { + gsonBuilder.create() + } {{/gson}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache new file mode 100644 index 00000000000..a1ebc2cfced --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache @@ -0,0 +1,13 @@ +package {{packageName}}.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +{{#nonPublicApi}}internal {{/nonPublicApi}}class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache similarity index 93% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApiClient.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache index d4b5a587d4c..2dbb50da9f3 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache @@ -249,4 +249,24 @@ import java.io.File ) } } + + protected inline fun parseDateToQueryString(value : T): String { + {{#toJson}} + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + {{#moshi}} + return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "") + {{/moshi}} + {{#gson}} + return Serializer.gson.toJson(value, T::class.java).replace("\"", "") + {{/gson}} + {{/toJson}} + {{^toJson}} + return value.toString() + {{/toJson}} + } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApiInfrastructureResponse.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiInfrastructureResponse.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApiInfrastructureResponse.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiInfrastructureResponse.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApplicationDelegates.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ApplicationDelegates.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache new file mode 100644 index 00000000000..45b9a9e3f32 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package {{packageName}}.infrastructure + +import java.lang.RuntimeException + +{{#nonPublicApi}}internal {{/nonPublicApi}}open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { + private const val serialVersionUID: Long = 123L + } +} + +{{#nonPublicApi}}internal {{/nonPublicApi}}open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ResponseExtensions.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ResponseExtensions.kt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/ResponseExtensions.kt.mustache rename to modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ResponseExtensions.kt.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache new file mode 100644 index 00000000000..66938213465 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache @@ -0,0 +1,38 @@ +package {{apiPackage}} + +import {{packageName}}.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import okhttp3.ResponseBody +import okhttp3.MultipartBody + +{{#imports}}import {{import}} +{{/imports}} + +{{#operations}} +interface {{classname}} { + {{#operation}} + {{#isDeprecated}} + @Deprecated("This api was deprecated") + {{/isDeprecated}} + {{#formParams}} + {{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}} + {{/-first}} + {{/formParams}} + {{^formParams}} + {{#prioritizedContentTypes}} + {{#-first}} + @Headers({ + "Content-Type:{{{mediaType}}}" + }) + {{/-first}} + {{/prioritizedContentTypes}} + {{/formParams}} + @{{httpMethod}}("{{{path}}}") + fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/allParams}}: Call<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}> + + {{/operation}} +} +{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache new file mode 100644 index 00000000000..079fbb1169b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@Body {{paramName}}: {{{dataType}}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache new file mode 100644 index 00000000000..5a7f687061d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field("{{baseName}}"){{/isMultipart}} {{paramName}}: MultipartBody.Part {{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache new file mode 100644 index 00000000000..2b26c446678 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@Header("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache new file mode 100644 index 00000000000..eab46f77ad4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache @@ -0,0 +1,43 @@ +package {{packageName}}.infrastructure + +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import retrofit2.converter.scalars.ScalarsConverterFactory +{{#gson}} +import retrofit2.converter.gson.GsonConverterFactory +{{/gson}} +{{#moshi}} +import retrofit2.converter.moshi.MoshiConverterFactory +{{/moshi}} + +{{#nonPublicApi}}internal {{/nonPublicApi}}class ApiClient( + private var baseUrl: String = "{{{basePath}}}", + private var okHttpClient: OkHttpClient +) { + init { + normalizeBaseUrl() + } + + val retrofitBuilder: Retrofit.Builder by lazy { + + Retrofit.Builder() + .baseUrl(baseUrl) + .addConverterFactory(ScalarsConverterFactory.create()) + {{#gson}} + .addConverterFactory(GsonConverterFactory.create(Serializer.gson)) + {{/gson}} + {{#moshi}} + .addConverterFactory(MoshiConverterFactory.create(Serializer.moshi)) + {{/moshi}} + } + + fun createService(serviceClass: Class): S { + return retrofitBuilder.client(okHttpClient).build().create(serviceClass) + } + + private fun normalizeBaseUrl() { + if (!baseUrl.endsWith("/")) { + baseUrl += "/" + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache new file mode 100644 index 00000000000..659f2df4851 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache @@ -0,0 +1,56 @@ +package {{packageName}}.infrastructure + +class CollectionFormats { + + open class CSVParams { + + var params: List + + constructor(params: List) { + this.params = params + } + + constructor(vararg params: String) { + this.params = listOf(*params) + } + + override fun toString(): String { + return params.joinToString(",") + } + } + + open class SSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString(" ") + } + } + + class TSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("\t") + } + } + + class PIPESParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("|") + } + } + + class SPACEParams : SSVParams() +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache new file mode 100644 index 00000000000..996a45473a9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@Path("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache new file mode 100644 index 00000000000..14c40f05e58 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@Query("{{baseName}}") {{paramName}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Errors.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Errors.kt.mustache deleted file mode 100644 index e1043e95b1f..00000000000 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/Errors.kt.mustache +++ /dev/null @@ -1,42 +0,0 @@ -@file:Suppress("unused") -package {{packageName}}.infrastructure - -import java.lang.RuntimeException - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private const val serialVersionUID: Long = 123L - } -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private const val serialVersionUID: Long = 456L - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/UUIDAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/UUIDAdapter.kt.mustache deleted file mode 100644 index ad442305b17..00000000000 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm/infrastructure/UUIDAdapter.kt.mustache +++ /dev/null @@ -1,51 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -{{#gson}} -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -{{/gson}} -import java.util.UUID - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class UUIDAdapter { - @ToJson - fun toJson(uuid: UUID) = uuid.toString() - - @FromJson - fun fromJson(s: String) = UUID.fromString(s) -} -{{/moshi}} -{{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class UUIDAdapter : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: UUID?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(value.toString()) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): UUID? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return UUID.fromString(out.nextString()) - } - } - } -} -{{/gson}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/markdown-documentation/README.mustache b/modules/openapi-generator/src/main/resources/markdown-documentation/README.mustache new file mode 100644 index 00000000000..365e5e84fd2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/markdown-documentation/README.mustache @@ -0,0 +1,57 @@ +# Documentation for {{appName}} + +{{#generateApiDocs}} + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**](Apis/{{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/generateApiDocs}} + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}](Models/{{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} + +{{! TODO: optional documentation for authorization? }} +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} + Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/markdown-documentation/api.mustache b/modules/openapi-generator/src/main/resources/markdown-documentation/api.mustache new file mode 100644 index 00000000000..725f3fd5688 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/markdown-documentation/api.mustache @@ -0,0 +1,42 @@ +# {{classname}}{{#description}} + {{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{summary}}{{#notes}} + + {{notes}}{{/notes}} + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{modelPackage}}/{{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{modelPackage}}/{{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/markdown-documentation/model.mustache b/modules/openapi-generator/src/main/resources/markdown-documentation/model.mustache new file mode 100644 index 00000000000..cee30af8aef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/markdown-documentation/model.mustache @@ -0,0 +1,19 @@ +{{#models}} +{{#model}} +# {{{packageName}}}.{{modelPackage}}.{{{classname}}} +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#parent}} +{{#parentVars}} +**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/parentVars}} +{{/parent}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + {{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache index 6d28900f862..cc4f128875f 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache @@ -42,10 +42,12 @@ "scripts": { "test": [ "@test-apis", - "@test-models" + "@test-models", + "@test-mock" ], "test-apis": "phpunit --testsuite Apis", "test-models": "phpunit --testsuite Models", + "test-mock": "phpunit --testsuite Mock", "phpcs": "phpcs", "phplint": "phplint ./ --exclude=vendor" } diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache new file mode 100644 index 00000000000..80d6cd2e9db --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache @@ -0,0 +1,371 @@ +mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + return $this->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + case IMocker::DATA_TYPE_STRING: + $minLength = $options['minLength'] ?? 0; + $maxLength = $options['maxLength'] ?? null; + return $this->mockString($dataFormat, $minLength, $maxLength); + case IMocker::DATA_TYPE_BOOLEAN: + return $this->mockBoolean(); + case IMocker::DATA_TYPE_ARRAY: + $items = $options['items'] ?? null; + $minItems = $options['minItems'] ?? 0; + $maxItems = $options['maxItems'] ?? null; + $uniqueItems = $options['uniqueItems'] ?? false; + return $this->mockArray($items, $minItems, $maxItems, $uniqueItems); + default: + throw new InvalidArgumentException('"dataType" must be one of ' . implode(', ', [ + IMocker::DATA_TYPE_INTEGER, + IMocker::DATA_TYPE_NUMBER, + IMocker::DATA_TYPE_STRING, + IMocker::DATA_TYPE_BOOLEAN, + IMocker::DATA_TYPE_ARRAY, + ])); + } + } + + /** + * Shortcut to mock integer type + * Equivalent to mockData(DATA_TYPE_INTEGER); + * + * @param string|null $dataFormat (optional) int32 or int64 + * @param number|null $minimum (optional) Default is 0 + * @param number|null $maximum (optional) Default is mt_getrandmax() + * @param bool|null $exclusiveMinimum (optional) Default is false + * @param bool|null $exclusiveMaximum (optional) Default is false + * + * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided + * + * @return int + */ + public function mockInteger( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 0); + } + + /** + * Shortcut to mock number type + * Equivalent to mockData(DATA_TYPE_NUMBER); + * + * @param string|null $dataFormat (optional) float or double + * @param number|null $minimum (optional) Default is 0 + * @param number|null $maximum (optional) Default is mt_getrandmax() + * @param bool|null $exclusiveMinimum (optional) Default is false + * @param bool|null $exclusiveMaximum (optional) Default is false + * + * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided + * + * @return float + */ + public function mockNumber( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 4); + } + + /** + * Shortcut to mock string type + * Equivalent to mockData(DATA_TYPE_STRING); + * + * @param string|null $dataFormat (optional) one of byte, binary, date, date-time, password + * @param int|null $minLength (optional) Default is 0 + * @param int|null $maxLength (optional) Default is 100 chars + * @param array $enum (optional) This array should have at least one element. + * Elements in the array should be unique. + * @param string|null $pattern (optional) This string should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * Recall: regular expressions are not implicitly anchored. + * + * @throws \InvalidArgumentException when invalid arguments passed + * + * @return string + */ + public function mockString( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null, + $pattern = null + ) { + if ($enum !== null) { + if ( + is_array($enum) === false + || empty($enum) + || count($enum) > count(array_unique($enum)) + ) { + throw new InvalidArgumentException('"enum" must be an array. This array should have at least one element. Elements in the array should be unique.'); + } + + // return random variant + return $enum[mt_rand(0, count($enum) - 1)]; + } + + if ($minLength !== 0 && $minLength !== null) { + if (is_int($minLength) === false) { + throw new InvalidArgumentException('"minLength" must be an integer'); + } elseif ($minLength < 0) { + throw new InvalidArgumentException('"minLength" must be greater than, or equal to, 0'); + } + } else { + $minLength = 0; + } + + if ($maxLength !== null) { + if (is_int($maxLength) === false) { + throw new InvalidArgumentException('"maxLength" must be an integer'); + } elseif ($maxLength < 0) { + throw new InvalidArgumentException('"maxLength" must be greater than, or equal to, 0'); + } + } else { + // since we don't need huge texts by default, lets cut them down to 100 chars + $maxLength = 100; + } + + if ($maxLength < $minLength) { + throw new InvalidArgumentException('"maxLength" value cannot be less than "minLength"'); + } + + return str_pad('', mt_rand($minLength, $maxLength), 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', \STR_PAD_RIGHT); + } + + /** + * Shortcut to mock boolean type + * Equivalent to mockData(DATA_TYPE_BOOLEAN); + * + * @return bool + */ + public function mockBoolean() + { + return (bool) mt_rand(0, 1); + } + + /** + * Shortcut to mock array type + * Equivalent to mockData(DATA_TYPE_ARRAY); + * + * @param array $items Array of described items + * @param int|null $minItems (optional) An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. + * @param int|null $maxItems (optional) An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword + * @param bool|null $uniqueItems (optional) If it has boolean value true, the instance validates successfully if all of its elements are unique + * + * @throws \InvalidArgumentException when invalid arguments passed + * + * @return array + */ + public function mockArray( + $items, + $minItems = 0, + $maxItems = null, + $uniqueItems = false + ) { + $arr = []; + $minSize = 0; + $maxSize = \PHP_INT_MAX; + + if (is_array($items) === false || array_key_exists('type', $items) === false) { + throw new InvalidArgumentException('"items" must be assoc array with "type" key'); + } + + if ($minItems !== null) { + if (is_integer($minItems) === false || $minItems < 0) { + throw new InvalidArgumentException('"mitItems" must be an integer. This integer must be greater than, or equal to, 0'); + } + $minSize = $minItems; + } + + if ($maxItems !== null) { + if (is_integer($maxItems) === false || $maxItems < 0) { + throw new InvalidArgumentException('"maxItems" must be an integer. This integer must be greater than, or equal to, 0.'); + } + if ($maxItems < $minItems) { + throw new InvalidArgumentException('"maxItems" value cannot be less than "minItems"'); + } + $maxSize = $maxItems; + } + + $dataType = $items['type']; + $dataFormat = $items['format'] ?? null; + $options = $this->extractSchemaProperties($items); + + // always genarate smallest possible array to avoid huge JSON responses + $arrSize = ($maxSize < 1) ? $maxSize : max($minSize, 1); + while (count($arr) < $arrSize) { + $arr[] = $this->mock($dataType, $dataFormat, $options); + } + return $arr; + } + + /** + * @internal Extract OAS properties from array or object. + * + * @param array $arr Processed array + * + * @return array + */ + private function extractSchemaProperties($arr) + { + $props = []; + foreach ( + [ + 'minimum', + 'maximum', + 'exclusiveMinimum', + 'exclusiveMaximum', + 'minLength', + 'maxLength', + 'pattern', + 'enum', + 'items', + 'minItems', + 'maxItems', + 'uniqueItems', + 'properties', + 'minProperties', + 'maxProperties', + 'additionalProperties', + 'required', + 'example', + ] as $propName + ) { + if (array_key_exists($propName, $arr)) { + $props[$propName] = $arr[$propName]; + } + } + return $props; + } + + /** + * @internal + * + * @return float|int + */ + protected function getRandomNumber( + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $maxDecimals = 4 + ) { + $min = 0; + $max = mt_getrandmax(); + + if ($minimum !== null) { + if (is_numeric($minimum) === false) { + throw new InvalidArgumentException('"minimum" must be a number'); + } + $min = $minimum; + } + + if ($maximum !== null) { + if (is_numeric($maximum) === false) { + throw new InvalidArgumentException('"maximum" must be a number'); + } + $max = $maximum; + } + + if ($exclusiveMinimum !== false) { + if (is_bool($exclusiveMinimum) === false) { + throw new InvalidArgumentException('"exclusiveMinimum" must be a boolean'); + } elseif ($minimum === null) { + throw new InvalidArgumentException('If "exclusiveMinimum" is present, "minimum" must also be present'); + } + $min += 1; + } + + if ($exclusiveMaximum !== false) { + if (is_bool($exclusiveMaximum) === false) { + throw new InvalidArgumentException('"exclusiveMaximum" must be a boolean'); + } elseif ($maximum === null) { + throw new InvalidArgumentException('If "exclusiveMaximum" is present, "maximum" must also be present'); + } + $max -= 1; + } + + if ($max < $min) { + throw new InvalidArgumentException('"maximum" value cannot be less than "minimum"'); + } + + if ($maxDecimals > 0) { + return round($min + mt_rand() / mt_getrandmax() * ($max - $min), $maxDecimals); + } + return mt_rand($min, $max); + } +} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache new file mode 100644 index 00000000000..e94d55f1afd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache @@ -0,0 +1,213 @@ +assertInternalType($expectedType, $mocker->mock($dataType)); + } + + public function provideMockCorrectArguments() + { + return [ + [IMocker::DATA_TYPE_INTEGER, null, null, IsType::TYPE_INT], + [IMocker::DATA_TYPE_NUMBER, null, null, IsType::TYPE_FLOAT], + [IMocker::DATA_TYPE_STRING, null, null, IsType::TYPE_STRING], + [IMocker::DATA_TYPE_BOOLEAN, null, null, IsType::TYPE_BOOL], + ]; + } + + /** + * @dataProvider provideMockIntegerCorrectArguments + * @covers ::mockInteger + */ + public function testMockIntegerWithCorrectArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + + $this->internalAssertNumber( + $integer, + $minimum, + $maximum, + $exclusiveMinimum, + $exclusiveMaximum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockIntegerCorrectArguments() + { + $types = [ + IsType::TYPE_INT, + IsType::TYPE_NUMERIC, + IsType::TYPE_SCALAR, + ]; + $notTypes = [ + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_FLOAT, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_STRING, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, -100, 100, false, false, $types, $notTypes], + [null, -100, null, false, false, $types, $notTypes], + [null, null, 100, false, false, $types, $notTypes], + [null, -99.5, null, true, false, $types, $notTypes], + [null, null, 99.5, false, true, $types, $notTypes], + [null, -99.5, 99.5, true, true, $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockIntegerInvalidArguments + * @covers ::mockInteger + * @expectedException \InvalidArgumentException + */ + public function testMockIntegerWithInvalidArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + $mocker = new OpenApiDataMocker(); + $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + + public function provideMockIntegerInvalidArguments() + { + return [ + [null, 'foo', null, false, false], + [null, null, false, false, false], + [null, null, null, true, false], + [null, null, null, false, true], + [null, 100, -100, false, false], + ]; + } + + /** + * @dataProvider provideMockNumberCorrectArguments + * @covers ::mockNumber + */ + public function testMockNumberWithCorrectArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + + $this->internalAssertNumber( + $number, + $minimum, + $maximum, + $exclusiveMinimum, + $exclusiveMaximum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockNumberCorrectArguments() + { + $types = [ + IsType::TYPE_SCALAR, + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + ]; + $notTypes = [ + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_STRING, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, -100, 100, false, false, $types, $notTypes], + [null, -100, null, false, false, $types, $notTypes], + [null, null, 100, false, false, $types, $notTypes], + [null, -99.5, null, true, false, $types, $notTypes], + [null, null, 99.5, false, true, $types, $notTypes], + [null, -99.5, 99.5, true, true, $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockNumberInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockNumber + */ + public function testMockNumberWithInvalidArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + $mocker = new OpenApiDataMocker(); + $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + + public function provideMockNumberInvalidArguments() + { + return [ + [null, 'foo', null, false, false], + [null, null, false, false, false], + [null, null, null, true, false], + [null, null, null, false, true], + [null, 100, -100, false, false], + ]; + } + + /** + * @dataProvider provideMockStringCorrectArguments + * @covers ::mockString + */ + public function testMockStringWithCorrectArguments( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); + + $this->internalAssertString( + $str, + $minLength, + $maxLength, + $enum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockStringCorrectArguments() + { + $types = [ + IsType::TYPE_SCALAR, + IsType::TYPE_STRING, + ]; + $notTypes = [ + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, 0, null, null, $types, $notTypes], + [null, 10, null, null, $types, $notTypes], + [null, 0, 100, null, $types, $notTypes], + [null, 10, 50, null, $types, $notTypes], + [null, 10, 10, null, $types, $notTypes], + [null, 0, 0, null, $types, $notTypes], + [null, null, null, null, $types, $notTypes], + [null, null, null, ['foobar', 'foobaz', 'hello world'], $types, $notTypes], + [null, null, null, ['foobar'], $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockStringInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockString + */ + public function testMockStringWithInvalidArguments( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null + ) { + $mocker = new OpenApiDataMocker(); + $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); + } + + public function provideMockStringInvalidArguments() + { + return [ + 'negative minLength' => [null, -10, null], + 'negative maxLength' => [null, 0, -10], + 'both minLength maxLength negative' => [null, -10, -10], + 'decimal minLength and maxLength' => [null, 0.5, 0.5], + 'string minLength' => [null, '10', null], + 'string maxLength' => [null, 0, '50'], + 'string minLength and maxLength' => [null, '10', '50'], + 'maxLength less than minLength' => [null, 50, 10], + 'enum is string' => [null, null, null, 'foobar'], + 'enum is empty array' => [null, null, null, []], + 'enum array is not unique' => [null, null, null, ['foobar', 'foobaz', 'foobar']], + ]; + } + + /** + * @covers ::mockBoolean + */ + public function testMockBoolean() + { + $mocker = new OpenApiDataMocker(); + $bool = $mocker->mockBoolean(); + + $matchingInternalTypes = [ + IsType::TYPE_SCALAR, + IsType::TYPE_BOOL, + ]; + + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $bool); + } + + $notMatchingInternalTypes = [ + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_STRING, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_CALLABLE, + ]; + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $bool); + } + } + + private function internalAssertNumber( + $number, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $number); + } + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $number); + } + + if ($minimum !== null) { + if ($exclusiveMinimum) { + $this->assertGreaterThan($minimum, $number); + } else { + $this->assertGreaterThanOrEqual($minimum, $number); + } + } + + if ($maximum !== null) { + if ($exclusiveMaximum) { + $this->assertLessThan($maximum, $number); + } else { + $this->assertLessThanOrEqual($maximum, $number); + } + } + } + + private function internalAssertString( + $str, + $minLength = null, + $maxLength = null, + $enum = null, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $str); + } + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $str); + } + + if ($minLength !== null) { + $this->assertGreaterThanOrEqual($minLength, mb_strlen($str, 'UTF-8')); + } + + if ($maxLength !== null) { + $this->assertLessThanOrEqual($maxLength, mb_strlen($str, 'UTF-8')); + } + + if (is_array($enum) && !empty($enum)) { + $this->assertContains($str, $enum); + } + } + + /** + * @dataProvider provideMockArrayCorrectArguments + * @covers ::mockArray + */ + public function testMockArrayFlattenWithCorrectArguments( + $items, + $minItems, + $maxItems, + $uniqueItems, + $expectedItemsType = null, + $expectedArraySize = null + ) { + $mocker = new OpenApiDataMocker(); + $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); + + $this->assertIsArray($arr); + if ($expectedArraySize !== null) { + $this->assertCount($expectedArraySize, $arr); + } + if ($expectedItemsType && $expectedArraySize > 0) { + $this->assertContainsOnly($expectedItemsType, $arr, true); + } + + $dataFormat = $items['dataFormat'] ?? null; + + // items field numeric properties + $minimum = $items['minimum'] ?? null; + $maximum = $items['maximum'] ?? null; + $exclusiveMinimum = $items['exclusiveMinimum'] ?? null; + $exclusiveMaximum = $items['exclusiveMaximum'] ?? null; + + // items field string properties + $minLength = $items['minLength'] ?? null; + $maxLength = $items['maxLength'] ?? null; + $enum = $items['enum'] ?? null; + $pattern = $items['pattern'] ?? null; + + // items field array properties + $subItems = $items['items'] ?? null; + $subMinItems = $items['minItems'] ?? null; + $subMaxItems = $items['maxItems'] ?? null; + $subUniqueItems = $items['uniqueItems'] ?? null; + + foreach ($arr as $item) { + switch ($items['type']) { + case IMocker::DATA_TYPE_INTEGER: + $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + break; + case IMocker::DATA_TYPE_NUMBER: + $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + break; + case IMocker::DATA_TYPE_STRING: + $this->internalAssertString($item, $minLength, $maxLength); + break; + case IMocker::DATA_TYPE_BOOLEAN: + $this->assertInternalType(IsType::TYPE_BOOL, $item); + break; + case IMocker::DATA_TYPE_ARRAY: + $this->testMockArrayFlattenWithCorrectArguments($subItems, $subMinItems, $subMaxItems, $subUniqueItems); + break; + } + } + } + + public function provideMockArrayCorrectArguments() + { + $intItems = ['type' => IMocker::DATA_TYPE_INTEGER, 'minimum' => 5, 'maximum' => 10]; + $floatItems = ['type' => IMocker::DATA_TYPE_NUMBER, 'minimum' => -32.4, 'maximum' => 88.6, 'exclusiveMinimum' => true, 'exclusiveMaximum' => true]; + $strItems = ['type' => IMocker::DATA_TYPE_STRING, 'minLength' => 20, 'maxLength' => 50]; + $boolItems = ['type' => IMocker::DATA_TYPE_BOOLEAN]; + $arrayItems = ['type' => IMocker::DATA_TYPE_ARRAY, 'items' => ['type' => IMocker::DATA_TYPE_STRING, 'minItems' => 3, 'maxItems' => 10]]; + $expectedInt = IsType::TYPE_INT; + $expectedFloat = IsType::TYPE_FLOAT; + $expectedStr = IsType::TYPE_STRING; + $expectedBool = IsType::TYPE_BOOL; + $expectedArray = IsType::TYPE_ARRAY; + + return [ + 'empty array' => [ + $strItems, null, 0, false, null, 0, + ], + 'empty array, limit zero' => [ + $strItems, 0, 0, false, null, 0, + ], + 'array of one string as default size' => [ + $strItems, null, null, false, $expectedStr, 1, + ], + 'array of one string, limit one' => [ + $strItems, 1, 1, false, $expectedStr, 1, + ], + 'array of two strings' => [ + $strItems, 2, null, false, $expectedStr, 2, + ], + 'array of five strings, limit ten' => [ + $strItems, 5, 10, false, $expectedStr, 5, + ], + 'array of five strings, limit five' => [ + $strItems, 5, 5, false, $expectedStr, 5, + ], + 'array of one string, limit five' => [ + $strItems, null, 5, false, $expectedStr, 1, + ], + 'array of one integer' => [ + $intItems, null, null, false, $expectedInt, 1, + ], + 'array of one float' => [ + $floatItems, null, null, false, $expectedFloat, 1, + ], + 'array of one boolean' => [ + $boolItems, null, null, false, $expectedBool, 1, + ], + 'array of one array of strings' => [ + $arrayItems, null, null, false, $expectedArray, 1, + ], + ]; + } + + /** + * @dataProvider provideMockArrayInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockArray + */ + public function testMockArrayWithInvalidArguments( + $items, + $minItems, + $maxItems, + $uniqueItems + ) { + $mocker = new OpenApiDataMocker(); + $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); + } + + public function provideMockArrayInvalidArguments() + { + $intItems = ['type' => IMocker::DATA_TYPE_INTEGER]; + + return [ + 'items is nor array' => [ + 'foobar', null, null, false, + ], + 'items doesnt have "type" key' => [ + ['foobar' => 'foobaz'], null, null, false, + ], + 'minItems is not integer' => [ + $intItems, 3.12, null, false, + ], + 'minItems is negative' => [ + $intItems, -10, null, false, + ], + 'minItems is not number' => [ + $intItems, '1', null, false, + ], + 'maxItems is not integer' => [ + $intItems, null, 3.12, false, + ], + 'maxItems is negative' => [ + $intItems, null, -10, false, + ], + 'maxItems is not number' => [ + $intItems, null, 'foobaz', false, + ], + 'maxItems less than minItems' => [ + $intItems, 5, 2, false, + ], + ]; + } +} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache index b8852944a12..81e19e73605 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache @@ -17,11 +17,15 @@ {{modelTestPath}} + + {{mockTestPath}} + {{apiSrcPath}} {{modelSrcPath}} + {{mockSrcPath}} diff --git a/modules/openapi-generator/src/main/resources/php/HeaderSelector.mustache b/modules/openapi-generator/src/main/resources/php/HeaderSelector.mustache index 76f82b67dbe..9b9a281b625 100644 --- a/modules/openapi-generator/src/main/resources/php/HeaderSelector.mustache +++ b/modules/openapi-generator/src/main/resources/php/HeaderSelector.mustache @@ -72,8 +72,8 @@ class HeaderSelector { if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { return null; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; + } elseif ($jsonAccept = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept)) { + return implode(',', $jsonAccept); } else { return implode(',', $accept); } diff --git a/modules/openapi-generator/src/main/resources/python/README.mustache b/modules/openapi-generator/src/main/resources/python/README.mustache index 144f72427e9..94d72af33dc 100644 --- a/modules/openapi-generator/src/main/resources/python/README.mustache +++ b/modules/openapi-generator/src/main/resources/python/README.mustache @@ -31,7 +31,7 @@ pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git Then import the package: ```python -import {{{packageName}}} +import {{{packageName}}} ``` ### Setuptools diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 6e02b238da1..b6a89d495d9 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -349,41 +349,37 @@ class Configuration(object): {{/servers}} ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/README.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/README.mustache new file mode 100644 index 00000000000..f26408cf661 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/README.mustache @@ -0,0 +1,55 @@ +# {{{projectName}}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements. + +Python 2.7 and 3.4+ + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`) + +Then import the package: +```python +import {{{packageName}}} +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import {{{packageName}}} +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +{{> python-experimental/README_common }} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/README_common.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/README_common.mustache new file mode 100644 index 00000000000..a8b66b0bed5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/README_common.mustache @@ -0,0 +1,74 @@ +```python +from __future__ import print_function +import time +import {{{packageName}}} +from pprint import pprint +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{> python_doc_auth_partial}} +# Defining host is optional and default to {{{basePath}}} +configuration.host = "{{{basePath}}}" +# Create an instance of the API class +api_instance = {{{packageName}}}.{{{classname}}}({{{packageName}}}.ApiClient(configuration)) +{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +try: +{{#summary}} # {{{.}}} +{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} + pprint(api_response){{/returnType}} +except {{{packageName}}}.ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{unescapedDescription}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} + All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} Authentication schemes defined for the API:{{/last}} +## {{{name}}} + +{{#isApiKey}} +- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}} +{{^isBasicBearer}} +- **Type**: HTTP basic authentication +{{/isBasicBearer}} +{{#isBasicBearer}} +- **Type**: Bearer authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} +{{/isBasicBearer}} +{{/isBasic}} +{{#isOAuth}} +- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/README_onlypackage.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/README_onlypackage.mustache new file mode 100644 index 00000000000..11c002c9aa5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/README_onlypackage.mustache @@ -0,0 +1,44 @@ +# {{{projectName}}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +The `{{packageName}}` package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements. + +Python 2.7 and 3.4+ + +## Installation & Usage + +This python library package is generated without supporting files like setup.py or requirements files + +To be able to use it, you will need these dependencies in your own package that uses this library: + +* urllib3 >= 1.15 +* six >= 1.10 +* certifi +* python-dateutil +{{#asyncio}} +* aiohttp +{{/asyncio}} +{{#tornado}} +* tornado>=4.2,<5 +{{/tornado}} + +## Getting Started + +In your own code, to use this library to connect and interact with {{{projectName}}}, +you can run the following: + +{{> python-experimental/README_common }} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/__init__model.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/__init__model.mustache new file mode 100644 index 00000000000..ca86cb8a624 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/__init__model.mustache @@ -0,0 +1,7 @@ +# coding: utf-8 + +# flake8: noqa +{{>partial_header}} + +# we can not import model classes here because that would create a circular +# reference which would not work in python2 diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/__init__package.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/__init__package.mustache new file mode 100644 index 00000000000..b5224a5821e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/__init__package.mustache @@ -0,0 +1,36 @@ +# coding: utf-8 + +# flake8: noqa + +{{>partial_header}} + +from __future__ import absolute_import + +__version__ = "{{packageVersion}}" + +# import apis into sdk package +{{#apiInfo}} +{{#apis}} +from {{apiPackage}}.{{classVarName}} import {{classname}} +{{/apis}} +{{/apiInfo}} + +# import ApiClient +from {{packageName}}.api_client import ApiClient + +# import Configuration +from {{packageName}}.configuration import Configuration + +# import exceptions +from {{packageName}}.exceptions import OpenApiException +from {{packageName}}.exceptions import ApiTypeError +from {{packageName}}.exceptions import ApiValueError +from {{packageName}}.exceptions import ApiKeyError +from {{packageName}}.exceptions import ApiException + +# import models into sdk package +{{#models}} +{{#model}} +from {{modelPackage}}.{{classFilename}} import {{unescapedDescription}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index 651559cf4ff..734c490caba 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -5,6 +5,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc.mustache index 5cc638a2eb6..4feb612f1c6 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc.mustache @@ -35,19 +35,16 @@ Method | HTTP request | Description {{#isOAuth}} * OAuth Authentication ({{name}}): {{/isOAuth }} -{{> api_doc_example }} {{/authMethods}} {{/hasAuthMethods}} -{{^hasAuthMethods}} -{{> api_doc_example }} -{{/hasAuthMethods}} +{{> python-experimental/api_doc_example }} ### Parameters {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#requiredParams}}{{^defaultValue}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | -{{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | defaults to {{{.}}} -{{/defaultValue}}{{/requiredParams}}{{#optionalParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | [optional]{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} +{{#requiredParams}}{{^defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | +{{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | defaults to {{{.}}} +{{/defaultValue}}{{/requiredParams}}{{#optionalParams}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | [optional]{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} {{/optionalParams}} ### Return type diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc_example.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc_example.mustache index e5eeee6b0ef..8a6beabd2d7 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc_example.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api_doc_example.mustache @@ -2,7 +2,6 @@ from __future__ import print_function import time import {{{packageName}}} -from {{{packageName}}}.rest import ApiException from pprint import pprint {{> python_doc_auth_partial}} {{#hasAuthMethods}} @@ -18,40 +17,40 @@ api_instance = {{{packageName}}}.{{{classname}}}() {{#requiredParams}}{{^defaultValue}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}} {{/defaultValue}}{{/requiredParams}}{{#optionalParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} {{/optionalParams}} - {{#requiredParams}} {{^hasMore}} + # example passing only required values which don't have defaults set try: {{#summary}} # {{{.}}} {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/defaultValue}}{{/requiredParams}}){{#returnType}} pprint(api_response){{/returnType}} -except ApiException as e: +except {{{packageName}}}.ApiException as e: print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) {{/hasMore}} {{/requiredParams}} - {{#optionalParams}} {{^hasMore}} + # example passing only required values which don't have defaults set # and optional values try: {{#summary}} # {{{.}}} {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#optionalParams}}{{paramName}}={{paramName}}{{#hasMore}}, {{/hasMore}}{{/optionalParams}}){{#returnType}} pprint(api_response){{/returnType}} -except ApiException as e: +except {{{packageName}}}.ApiException as e: print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) {{/hasMore}} {{/optionalParams}} - {{^requiredParams}} {{^optionalParams}} + # example, this endpoint has no required or optional parameters try: {{#summary}} # {{{.}}} {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}(){{#returnType}} pprint(api_response){{/returnType}} -except ApiException as e: +except {{{packageName}}}.ApiException as e: print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) {{/optionalParams}} {{/requiredParams}} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache index 2513d6b3f86..0ca198ddf96 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache @@ -2,37 +2,31 @@ {{>partial_header}} -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from {{packageName}}.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from {{packageName}}.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -{{#models}}{{#model}}{{#imports}}{{.}} -{{/imports}}{{/model}}{{/models}} - {{#models}} {{#model}} +{{#imports}} +{{{.}}} +{{/imports}} + + {{^interfaces}} {{#isAlias}} {{> python-experimental/model_templates/model_simple }} @@ -43,7 +37,7 @@ from {{packageName}}.model_utils import ( # noqa: F401 {{/interfaces}} {{#interfaces}} {{#-last}} -{{> python-experimental/model_templates/model_normal }} +{{> python-experimental/model_templates/model_composed }} {{/-last}} {{/interfaces}} {{/model}} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_doc.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_doc.mustache index 79abbf61300..a1e57131bc4 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_doc.mustache @@ -7,16 +7,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- {{#requiredVars}} {{^defaultValue}} -**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}} +**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}} {{/defaultValue}} {{/requiredVars}} {{#requiredVars}} {{#defaultValue}} -**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}} +**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}} {{/defaultValue}} {{/requiredVars}} {{#optionalVars}} -**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} +**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} {{/optionalVars}} {{#additionalPropertiesType}} **any string name** | **{{additionalPropertiesType}}** | any string name can be used but the value must be the correct type | [optional] diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_allowed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_allowed.mustache deleted file mode 100644 index 2414be114a3..00000000000 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_allowed.mustache +++ /dev/null @@ -1,16 +0,0 @@ - allowed_values = { -{{#allVars}} -{{#isEnum}} - ('{{name}}',): { -{{#isNullable}} - 'None': None, -{{/isNullable}} -{{#allowableValues}} -{{#enumVars}} - '{{name}}': {{{value}}}, -{{/enumVars}} -{{/allowableValues}} - }, -{{/isEnum}} -{{/allVars}} - } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_openapi_validations.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_openapi_validations.mustache deleted file mode 100644 index 1cc7b585507..00000000000 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvar_openapi_validations.mustache +++ /dev/null @@ -1,42 +0,0 @@ - openapi_types = { -{{#allVars}} - '{{name}}': ({{{dataType}}},), # noqa: E501 -{{/allVars}} - } - - validations = { -{{#allVars}} -{{#hasValidation}} - ('{{name}}',): { -{{#maxLength}} - 'max_length': {{maxLength}}, -{{/maxLength}} -{{#minLength}} - 'min_length': {{minLength}}, -{{/minLength}} -{{#maxItems}} - 'max_items': {{maxItems}}, -{{/maxItems}} -{{#minItems}} - 'min_items': {{minItems}}, -{{/minItems}} -{{#maximum}} - {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}}, -{{/maximum}} -{{#minimum}} - {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}}, -{{/minimum}} -{{#pattern}} - 'regex': { - 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}} - {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}} - }, -{{/pattern}} - }, -{{/hasValidation}} -{{/allVars}} - } - - additional_properties_type = {{#additionalPropertiesType}}({{{additionalPropertiesType}}},) # noqa: E501{{/additionalPropertiesType}}{{^additionalPropertiesType}}None{{/additionalPropertiesType}} - - discriminator = {{#discriminator}}'{{{discriminatorName}}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvars.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvars.mustache new file mode 100644 index 00000000000..fcd8a71fd12 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/classvars.mustache @@ -0,0 +1,119 @@ + allowed_values = { +{{#requiredVars}} +{{#isEnum}} + ('{{name}}',): { +{{#isNullable}} + 'None': None, +{{/isNullable}} +{{#allowableValues}} +{{#enumVars}} + '{{name}}': {{{value}}}, +{{/enumVars}} +{{/allowableValues}} + }, +{{/isEnum}} +{{/requiredVars}} +{{#optionalVars}} +{{#isEnum}} + ('{{name}}',): { +{{#isNullable}} + 'None': None, +{{/isNullable}} +{{#allowableValues}} +{{#enumVars}} + '{{name}}': {{{value}}}, +{{/enumVars}} +{{/allowableValues}} + }, +{{/isEnum}} +{{/optionalVars}} + } + + openapi_types = { +{{#requiredVars}} + '{{name}}': ({{{dataType}}},), # noqa: E501 +{{/requiredVars}} +{{#optionalVars}} + '{{name}}': ({{{dataType}}},), # noqa: E501 +{{/optionalVars}} + } + + validations = { +{{#requiredVars}} +{{#hasValidation}} + ('{{name}}',): { +{{#maxLength}} + 'max_length': {{maxLength}}, +{{/maxLength}} +{{#minLength}} + 'min_length': {{minLength}}, +{{/minLength}} +{{#maxItems}} + 'max_items': {{maxItems}}, +{{/maxItems}} +{{#minItems}} + 'min_items': {{minItems}}, +{{/minItems}} +{{#maximum}} + {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}}, +{{/maximum}} +{{#minimum}} + {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}}, +{{/minimum}} +{{#pattern}} + 'regex': { + 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}} + {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}} + }, +{{/pattern}} + }, +{{/hasValidation}} +{{/requiredVars}} +{{#optionalVars}} +{{#hasValidation}} + ('{{name}}',): { +{{#maxLength}} + 'max_length': {{maxLength}}, +{{/maxLength}} +{{#minLength}} + 'min_length': {{minLength}}, +{{/minLength}} +{{#maxItems}} + 'max_items': {{maxItems}}, +{{/maxItems}} +{{#minItems}} + 'min_items': {{minItems}}, +{{/minItems}} +{{#maximum}} + {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}}, +{{/maximum}} +{{#minimum}} + {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}}, +{{/minimum}} +{{#pattern}} + 'regex': { + 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}} + {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}} + }, +{{/pattern}} + }, +{{/hasValidation}} +{{/optionalVars}} + } + + additional_properties_type = {{#additionalPropertiesType}}({{{additionalPropertiesType}}},) # noqa: E501{{/additionalPropertiesType}}{{^additionalPropertiesType}}None{{/additionalPropertiesType}} + + @staticmethod + def discriminator(): + return {{^discriminator}}None{{/discriminator}}{{#discriminator}}{ + '{{{discriminatorName}}}': { +{{#children}} + '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': {{{classname}}}, +{{/children}} +{{^children}} +{{#mappedModels}} + '{{mappingName}}': {{{modelName}}}, +{{/mappedModels}} +{{/children}} + }, + }{{/discriminator}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_discriminator.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_discriminator.mustache new file mode 100644 index 00000000000..c4baa722ffb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_discriminator.mustache @@ -0,0 +1,12 @@ + @classmethod + def get_discriminator_class(cls, from_server, data): + """Returns the child class specified by the discriminator""" + discriminator = cls.discriminator() + discr_propertyname_py = list(discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if from_server: + class_name = data[discr_propertyname_js] + else: + class_name = data[discr_propertyname_py] + class_name_to_discr_class = discriminator[discr_propertyname_py] + return class_name_to_discr_class.get(class_name) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache new file mode 100644 index 00000000000..5ed5993fe9f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache @@ -0,0 +1,42 @@ + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + +{{> python-experimental/model_templates/method_init_shared }} + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { +{{#requiredVars}} + '{{name}}': {{name}}, +{{/requiredVars}} + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + +{{#requiredVars}} + self.{{name}} = {{name}} +{{/requiredVars}} + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_normal.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_normal.mustache new file mode 100644 index 00000000000..b053427a799 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_normal.mustache @@ -0,0 +1,21 @@ + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + +{{> python-experimental/model_templates/method_init_shared }} + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + +{{#requiredVars}} + self.{{name}} = {{name}} +{{/requiredVars}} + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache new file mode 100644 index 00000000000..2f3b70ea690 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache @@ -0,0 +1,23 @@ + def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{#defaultValue}}, {{name}}={{{defaultValue}}}{{/defaultValue}}{{/requiredVars}}, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + +{{#requiredVars}}{{^hasMore}} Args:{{/hasMore}}{{/requiredVars}}{{#requiredVars}}{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}{{/description}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{^hasMore}} +{{/hasMore}}{{/requiredVars}} + Keyword Args:{{#requiredVars}}{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}] # noqa: E501{{/defaultValue}}{{/requiredVars}} + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done.{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501{{/optionalVars}} + """ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_set_attribute.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_set_attribute.mustache new file mode 100644 index 00000000000..f4a36e42f25 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_set_attribute.mustache @@ -0,0 +1,49 @@ + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._from_server, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value + ) + self.__dict__['_data_store'][name] = value \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_init_properties.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_init_properties.mustache deleted file mode 100644 index dab632efab0..00000000000 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_init_properties.mustache +++ /dev/null @@ -1,126 +0,0 @@ - def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{#defaultValue}}, {{name}}={{{defaultValue}}}{{/defaultValue}}{{/requiredVars}}, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """{{classname}} - a model defined in OpenAPI - -{{#requiredVars}}{{^hasMore}} Args:{{/hasMore}}{{/requiredVars}}{{#requiredVars}}{{^defaultValue}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}{{/description}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{^hasMore}} -{{/hasMore}}{{/requiredVars}} - Keyword Args:{{#requiredVars}}{{#defaultValue}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}] # noqa: E501{{/defaultValue}}{{/requiredVars}} - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _from_server (bool): True if the data is from the server - False if the data is from the client (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done.{{#optionalVars}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501{{/optionalVars}} - """ - self._data_store = {} - self._check_type = _check_type - self._from_server = _from_server - self._path_to_item = _path_to_item - self._configuration = _configuration - -{{#requiredVars}} - self.__set_item('{{name}}', {{name}}) -{{/requiredVars}} - for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) -{{#allVars}} - - @property - def {{name}}(self): - """Gets the {{name}} of this {{classname}}. # noqa: E501 -{{#description}} - {{{description}}} # noqa: E501 -{{/description}} - - Returns: - ({{{dataType}}}): The {{name}} of this {{classname}}. # noqa: E501 - """ - return self.__get_item('{{name}}') - - @{{name}}.setter - def {{name}}(self, value): - """Sets the {{name}} of this {{classname}}. # noqa: E501 -{{#description}} - {{{description}}} # noqa: E501 -{{/description}} - """ - return self.__set_item('{{name}}', value) -{{/allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache new file mode 100644 index 00000000000..e5eee88a960 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache @@ -0,0 +1,61 @@ + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + # set the attribute on the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + if model_instances: + for model_instance in model_instances: + if model_instance == self: + self.set_attribute(name, value) + else: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = ( + model_instance + ) + return None + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + if model_instances: + values = set() + for model_instance in model_instances: + if name in model_instance._data_store: + values.add(model_instance._data_store[name]) + if len(values) == 1: + return list(values)[0] + raise ApiValueError( + "Values stored for property {0} in {1} difffer when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + path_to_item + ) + + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_normal.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_normal.mustache new file mode 100644 index 00000000000..f92663ab208 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_normal.mustache @@ -0,0 +1,24 @@ + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + if name in self.__dict__['_data_store']: + return self.__dict__['_data_store'][name] + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + [name] + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_shared.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_shared.mustache new file mode 100644 index 00000000000..d3cf66e41b6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_shared.mustache @@ -0,0 +1,15 @@ + def __setitem__(self, name, value): + """this allows us to set values with instance[field_name] = val""" + self.__setattr__(name, value) + + def __getitem__(self, name): + """this allows us to get a value with val = instance[field_name]""" + return self.__getattr__(name) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_todict_tostr_eq_shared.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_todict_tostr_eq_shared.mustache new file mode 100644 index 00000000000..d01d49ad77c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_todict_tostr_eq_shared.mustache @@ -0,0 +1,29 @@ + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in six.iteritems(self._data_store): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if (not six.PY3 and + len(types) == 2 and unicode in types): # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_tostr_eq_simple.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_tostr_eq_simple.mustache new file mode 100644 index 00000000000..0bba565d22c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_tostr_eq_simple.mustache @@ -0,0 +1,22 @@ + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_composed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_composed.mustache new file mode 100644 index 00000000000..d53d89cef2b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_composed.mustache @@ -0,0 +1,56 @@ +class {{unescapedDescription}}(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: +{{> python-experimental/model_templates/docstring_allowed }} + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. +{{> python-experimental/model_templates/docstring_openapi_validations }} + """ + +{{> python-experimental/model_templates/classvars }} + + attribute_map = { +{{#requiredVars}} + '{{name}}': '{{baseName}}', # noqa: E501 +{{/requiredVars}} +{{#optionalVars}} + '{{name}}': '{{baseName}}', # noqa: E501 +{{/optionalVars}} + } + +{{> python-experimental/model_templates/method_init_composed }} + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ +{{#anyOf}} + {{{.}}}, +{{/anyOf}} + ], + 'allOf': [ +{{#allOf}} + {{{.}}}, +{{/allOf}} + ], + 'oneOf': [ +{{#oneOf}} + {{{.}}}, +{{/oneOf}} + ], + }{{#discriminator}} + +{{> python-experimental/model_templates/method_discriminator }}{{/discriminator}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_normal.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_normal.mustache index c4e707e036e..8bfe6ada48d 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_normal.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_normal.mustache @@ -1,4 +1,4 @@ -class {{classname}}(ModelNormal): +class {{unescapedDescription}}(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -13,69 +13,21 @@ class {{classname}}(ModelNormal): {{> python-experimental/model_templates/docstring_openapi_validations }} """ -{{> python-experimental/model_templates/classvar_allowed }} +{{> python-experimental/model_templates/classvars }} attribute_map = { -{{#allVars}} - '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} # noqa: E501 -{{/allVars}} +{{#requiredVars}} + '{{name}}': '{{baseName}}', # noqa: E501 +{{/requiredVars}} +{{#optionalVars}} + '{{name}}': '{{baseName}}', # noqa: E501 +{{/optionalVars}} } -{{#discriminator}} - discriminator_value_class_map = { - {{#children}}'{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': {{{classname}}}{{^-last}}, - {{/-last}}{{/children}} - } -{{/discriminator}} + @staticmethod + def _composed_schemas(): + return None -{{> python-experimental/model_templates/classvar_openapi_validations }} +{{> python-experimental/model_templates/method_init_normal}}{{#discriminator}} -{{> python-experimental/model_templates/methods_init_properties }} -{{#discriminator}} - @classmethod - def get_real_child_model(cls, data): - """Returns the real base class specified by the discriminator - We assume that data has javascript keys - """ - discriminator_key = cls.attribute_map[cls.discriminator] - discriminator_value = data[discriminator_key] - return cls.discriminator_value_class_map.get(discriminator_value) - -{{/discriminator}} - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, {{classname}}): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other \ No newline at end of file +{{> python-experimental/model_templates/method_discriminator }}{{/discriminator}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_simple.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_simple.mustache index b5939d926c2..465918dfa5c 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/model_simple.mustache @@ -1,4 +1,4 @@ -class {{classname}}(ModelSimple): +class {{unescapedDescription}}(ModelSimple): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -9,38 +9,10 @@ class {{classname}}(ModelSimple): {{> python-experimental/model_templates/docstring_openapi_validations }} """ -{{> python-experimental/model_templates/classvar_allowed }} +{{> python-experimental/model_templates/classvars }} -{{> python-experimental/model_templates/classvar_openapi_validations }} + @staticmethod + def _composed_schemas(): + return None -{{> python-experimental/model_templates/methods_init_properties }} - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, {{classname}}): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other \ No newline at end of file +{{> python-experimental/model_templates/method_init_normal}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_test.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_test.mustache new file mode 100644 index 00000000000..4fd1263b5f2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_test.mustache @@ -0,0 +1,33 @@ +# coding: utf-8 + +{{>partial_header}} + +from __future__ import absolute_import + +import unittest + +{{#models}} +{{#model}} +import {{packageName}} + + +class Test{{unescapedDescription}}(unittest.TestCase): + """{{unescapedDescription}} unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test{{unescapedDescription}}(self): + """Test {{unescapedDescription}}""" + # FIXME: construct object with mandatory attributes with example values + # model = {{packageName}}.{{unescapedDescription}}() # noqa: E501 + pass + +{{/model}} +{{/models}} + +if __name__ == '__main__': + unittest.main() diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache index 101b5466c31..dbd592c37e8 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache @@ -2,10 +2,10 @@ {{>partial_header}} -import copy from datetime import date, datetime # noqa: F401 import inspect import os +import pprint import re import tempfile @@ -38,30 +38,52 @@ else: class OpenApiModel(object): """The base class for all OpenAPIModels""" +{{> python-experimental/model_templates/method_set_attribute }} + +{{> python-experimental/model_templates/methods_shared }} + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" +{{> python-experimental/model_templates/methods_setattr_getattr_normal }} + +{{> python-experimental/model_templates/methods_tostr_eq_simple }} + class ModelNormal(OpenApiModel): """the parent class of models whose type == object in their swagger/openapi""" +{{> python-experimental/model_templates/methods_setattr_getattr_normal }} + +{{> python-experimental/model_templates/methods_todict_tostr_eq_shared}} + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf""" + +{{> python-experimental/model_templates/methods_setattr_getattr_composed }} + +{{> python-experimental/model_templates/methods_todict_tostr_eq_shared}} + COERCION_INDEX_BY_TYPE = { - ModelNormal: 0, - ModelSimple: 1, - none_type: 2, - list: 3, - dict: 4, - float: 5, - int: 6, - bool: 7, - datetime: 8, - date: 9, - str: 10, - file_type: 11, + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, } # these are used to limit what type conversions we try to do @@ -70,6 +92,8 @@ COERCION_INDEX_BY_TYPE = { UPCONVERSION_TYPE_PAIRS = ( (str, datetime), (str, date), + (list, ModelComposed), + (dict, ModelComposed), (list, ModelNormal), (dict, ModelNormal), (str, ModelSimple), @@ -80,6 +104,8 @@ UPCONVERSION_TYPE_PAIRS = ( COERCIBLE_TYPE_PAIRS = { False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), # (dict, ModelNormal), # (list, ModelNormal), # (str, ModelSimple), @@ -94,6 +120,8 @@ COERCIBLE_TYPE_PAIRS = { # (float, str), ), True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), (dict, ModelNormal), (list, ModelNormal), (str, ModelSimple), @@ -336,6 +364,9 @@ def order_response_types(required_types): return COERCION_INDEX_BY_TYPE[list] elif isinstance(class_or_instance, dict): return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] elif (inspect.isclass(class_or_instance) and issubclass(class_or_instance, ModelNormal)): return COERCION_INDEX_BY_TYPE[ModelNormal] @@ -377,7 +408,9 @@ def remove_uncoercible(required_types_classes, current_item, from_server, # convert our models to OpenApiModel required_type_class_simplified = required_type_class if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelNormal): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): required_type_class_simplified = ModelNormal elif issubclass(required_type_class_simplified, ModelSimple): required_type_class_simplified = ModelSimple @@ -514,6 +547,21 @@ def deserialize_primitive(data, klass, path_to_item): ) +def fix_model_input_data(model_data, model_class): + # this is only called on classes where the input data is a dict + fixed_model_data = change_keys_js_to_python( + model_data, + model_class + ) + if model_class._composed_schemas() is not None: + for allof_class in model_class._composed_schemas()['allOf']: + fixed_model_data = change_keys_js_to_python( + fixed_model_data, + allof_class + ) + return fixed_model_data + + def deserialize_model(model_data, model_class, path_to_item, check_type, configuration, from_server): """Deserializes model_data to model instance. @@ -536,42 +584,29 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, ApiValueError ApiKeyError """ - fixed_model_data = copy.deepcopy(model_data) - - if isinstance(fixed_model_data, dict): - fixed_model_data = change_keys_js_to_python(fixed_model_data, - model_class) kw_args = dict(_check_type=check_type, _path_to_item=path_to_item, _configuration=configuration, _from_server=from_server) - if hasattr(model_class, 'get_real_child_model'): - # discriminator case - discriminator_class = model_class.get_real_child_model(model_data) - if discriminator_class: - if isinstance(model_data, list): - instance = discriminator_class(*model_data, **kw_args) - elif isinstance(model_data, dict): - fixed_model_data = change_keys_js_to_python( - fixed_model_data, - discriminator_class - ) - kw_args.update(fixed_model_data) - instance = discriminator_class(**kw_args) - else: - # all other cases - if isinstance(model_data, list): - instance = model_class(*model_data, **kw_args) - if isinstance(model_data, dict): - fixed_model_data = change_keys_js_to_python(fixed_model_data, - model_class) - kw_args.update(fixed_model_data) - instance = model_class(**kw_args) - else: - instance = model_class(model_data, **kw_args) + used_model_class = model_class + if model_class.discriminator() is not None: + used_model_class = model_class.get_discriminator_class( + from_server, model_data) + if issubclass(used_model_class, ModelSimple): + instance = used_model_class(value=model_data, **kw_args) + return instance + if isinstance(model_data, list): + instance = used_model_class(*model_data, **kw_args) + if isinstance(model_data, dict): + fixed_model_data = change_keys_js_to_python( + model_data, + used_model_class + ) + kw_args.update(fixed_model_data) + instance = used_model_class(**kw_args) return instance @@ -626,7 +661,7 @@ def attempt_convert_item(input_value, valid_classes, path_to_item, key_type (bool): if True we need to convert a key type (not supported) must_convert (bool): if True we must convert check_type (bool): if True we check the type or the returned data in - ModelNormal and ModelSimple instances + ModelComposed/ModelNormal/ModelSimple instances Returns: instance (any) the fixed item @@ -790,27 +825,31 @@ def model_to_dict(model_instance, serialize=True): """ result = {} - for attr, value in six.iteritems(model_instance._data_store): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: model_to_dict(x, serialize=serialize) - if hasattr(x, '_data_store') else x, value - )) - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], - model_to_dict(item[1], serialize=serialize)) - if hasattr(item[1], '_data_store') else item, - value.items() - )) - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value + model_instances = [model_instance] + if model_instance._composed_schemas() is not None: + model_instances = model_instance._composed_instances + for model_instance in model_instances: + for attr, value in six.iteritems(model_instance._data_store): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + attr = model_instance.attribute_map.get(attr, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: model_to_dict(x, serialize=serialize) + if hasattr(x, '_data_store') else x, value + )) + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], + model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], '_data_store') else item, + value.items() + )) + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value return result @@ -866,3 +905,235 @@ def get_py3_class_name(input_class): elif input_class == int: return 'int' return input_class.__name__ + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas()['allOf']: + + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python( + model_args, allof_class) + + # extract a dict of only required keys from fixed_model_args + kwargs = {} + var_names = set(allof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + allof_instance = allof_class(**kwargs) + composed_instances.append(allof_instance) + return composed_instances + + +def get_oneof_instance(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + oneof_instance (instance) + """ + oneof_instance = None + if len(self._composed_schemas()['oneOf']) == 0: + return oneof_instance + + for oneof_class in self._composed_schemas()['oneOf']: + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python( + model_args, oneof_class) + + # extract a dict of only required keys from fixed_model_args + kwargs = {} + var_names = set(oneof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + try: + oneof_instance = oneof_class(**kwargs) + break + except Exception: + pass + if oneof_instance is None: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Unable to " + "make any instances of the classes in oneOf definition." % + self.__class__.__name__ + ) + return oneof_instance + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas()['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas()['anyOf']: + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python(model_args, anyof_class) + + # extract a dict of only required keys from these_model_vars + kwargs = {} + var_names = set(anyof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + try: + anyof_instance = anyof_class(**kwargs) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Unable to " + "make any instances of the classes in anyOf definition." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_additional_properties_model_instances( + composed_instances, self): + additional_properties_model_instances = [] + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + if instance.additional_properties_type is not None: + additional_properties_model_instances.append(instance) + return additional_properties_model_instances + + +def get_var_name_to_model_instances(self, composed_instances): + var_name_to_model_instances = {} + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + for var_name in instance.openapi_types: + if var_name not in var_name_to_model_instances: + var_name_to_model_instances[var_name] = [instance] + else: + var_name_to_model_instances[var_name].append(instance) + return var_name_to_model_instances + + +def get_unused_args(self, composed_instances, model_args): + unused_args = dict(model_args) + # arguments apssed to self were already converted to python names + # before __init__ was called + for var_name_py in self.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + for instance in composed_instances: + if instance.__class__ in self._composed_schemas()['allOf']: + for var_name_py in instance.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + else: + for var_name_js in instance.attribute_map.values(): + if var_name_js in unused_args: + del unused_args[var_name_js] + return unused_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas/classes, validates the classes to make sure that + they do not share any of the same parameters. If there is no collision + then composed model instances are created and returned tot the calling + self model + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas() + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + + # map variable names to composed_instances + var_name_to_model_instances = get_var_name_to_model_instances( + self, composed_instances) + + # set additional_properties_model_instances + additional_properties_model_instances = ( + get_additional_properties_model_instances(composed_instances, self) + ) + + # set any remaining values + unused_args = get_unused_args(self, composed_instances, model_args) + if len(unused_args) > 0: + if len(additional_properties_model_instances) == 0: + raise ApiValueError( + "Invalid input arguments input when making an instance of " + "class %s. Not all inputs were used. The unused input data " + "is %s" % (self.__class__.__name__, unused_args) + ) + for var_name, var_value in six.iteritems(unused_args): + for instance in additional_properties_model_instances: + setattr(instance, var_name, var_value) + # no need to add additional_properties to var_name_to_model_instances here + # because additional_properties_model_instances will direct us to that + # instance when we use getattr or setattr + # and we update var_name_to_model_instances in setattr + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances + ] diff --git a/modules/openapi-generator/src/main/resources/python/tox.mustache b/modules/openapi-generator/src/main/resources/python/tox.mustache index 63d12fdeaea..585feb3c681 100644 --- a/modules/openapi-generator/src/main/resources/python/tox.mustache +++ b/modules/openapi-generator/src/main/resources/python/tox.mustache @@ -16,5 +16,5 @@ commands= [] {{/asyncio}} {{#asyncio}} - pytest -v --cov petstore_api + pytest -v --cov {{{packageName}}} {{/asyncio}} diff --git a/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache b/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache index 5b6417737e6..d2835cda099 100644 --- a/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache +++ b/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache @@ -3,3 +3,5 @@ ^\.openapi-generator-ignore$ ^\.travis\.yml$ ^\.openapi-generator$ +^docs$ +^git_push\.sh$ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/r/description.mustache b/modules/openapi-generator/src/main/resources/r/description.mustache index 42a07916a3d..129c6fc828e 100644 --- a/modules/openapi-generator/src/main/resources/r/description.mustache +++ b/modules/openapi-generator/src/main/resources/r/description.mustache @@ -3,7 +3,7 @@ Title: R Package Client for {{{appName}}} Version: {{packageVersion}} Authors@R: person("{{#infoName}}{{infoName}}{{/infoName}}{{^infoName}}OpenAPI Generator community{{/infoName}}", email = "{{#infoEmail}}{{infoEmail}}{{/infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}", role = c("aut", "cre")) Description: {{{appDescription}}}{{^appDescription}}R Package Client for {{{appName}}}{{/appDescription}} -Depends: R (>= 3.3.3) +Depends: R (>= 3.3) Encoding: UTF-8 License: {{#licenseInfo}}{{licenseInfo}}{{/licenseInfo}}{{^licenseInfo}}Unlicense{{/licenseInfo}} LazyData: true diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache index e10080d0205..bbd7ae48c31 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.module.mustache @@ -13,9 +13,9 @@ import { {{classname}} } from './{{importPath}}'; imports: [], declarations: [], exports: [], - providers: [ + providers: [{{^providedInRoot}} {{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}}, - {{/hasMore}}{{/apis}}{{/apiInfo}} ] + {{/hasMore}}{{/apis}}{{/apiInfo}} {{/providedInRoot}}] }) export class {{apiModuleClassName}} { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache index 7ab6c76bb2e..912ecf6e5ac 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache @@ -175,13 +175,13 @@ export class {{classname}} { {{/useHttpClient}} */ {{#useHttpClient}} - public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'body', reportProgress?: boolean): Observable<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; - public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'response', reportProgress?: boolean): Observable>; - public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'events', reportProgress?: boolean): Observable>; - public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe: any = 'body', reportProgress: boolean = false ): Observable { + public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: {{#produces}}'{{mediaType}}'{{#hasMore}} | {{/hasMore}}{{/produces}}{{^produces}}undefined{{/produces}}}): Observable<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; + public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: {{#produces}}'{{mediaType}}'{{#hasMore}} | {{/hasMore}}{{/produces}}{{^produces}}undefined{{/produces}}}): Observable>; + public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: {{#produces}}'{{mediaType}}'{{#hasMore}} | {{/hasMore}}{{/produces}}{{^produces}}undefined{{/produces}}}): Observable>; + public {{nickname}}({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: {{#produces}}'{{mediaType}}'{{#hasMore}} | {{/hasMore}}{{/produces}}{{^produces}}undefined{{/produces}}}): Observable { {{/useHttpClient}} {{^useHttpClient}} - public {{nickname}}WithHttpInfo({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}extraHttpRequestParams?: RequestOptionsArgs): Observable { + public {{nickname}}WithHttpInfo({{^useSingleRequestParameter}}{{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}{{/useSingleRequestParameter}}{{#useSingleRequestParameter}}{{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}RequestParams, {{/allParams.0}}{{/useSingleRequestParameter}}extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: {{#produces}}'{{mediaType}}'{{#hasMore}} | {{/hasMore}}{{/produces}}{{^produces}}undefined{{/produces}}}): Observable { {{/useHttpClient}} {{#allParams}} {{#useSingleRequestParameter}} @@ -217,7 +217,7 @@ export class {{classname}} { {{^isListContainer}} if ({{paramName}} !== undefined && {{paramName}} !== null) { {{#isDateTime}} - {{#useHttpClient}}queryParameters = {{/useHttpClient}}queryParameters.set('{{baseName}}', ({{paramName}} as any instanceof Date) ? ({{paramName}} as any).toISOString().substr(0, 10) : {{paramName}}); + {{#useHttpClient}}queryParameters = {{/useHttpClient}}queryParameters.set('{{baseName}}', ({{paramName}} as any instanceof Date) ? ({{paramName}} as any).toISOString(): {{paramName}}); {{/isDateTime}} {{^isDateTime}} {{#useHttpClient}}queryParameters = {{/useHttpClient}}queryParameters.set('{{baseName}}', {{paramName}}); @@ -282,13 +282,16 @@ export class {{classname}} { {{/isOAuth}} {{/authMethods}} - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - {{#produces}} - '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} - {{/produces}} - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + {{#produces}} + '{{{mediaType}}}'{{#hasMore}},{{/hasMore}} + {{/produces}} + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { {{^useHttpClient}} headers.set('Accept', httpHeaderAcceptSelected); diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache index a460d5ce588..db2738d890f 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache @@ -1,8 +1,10 @@ // tslint:disable {{>licenseInfo}} -{{#withSeparateModelsAndApi}}{{#imports}} -import { {{class}} } from './{{filename}}';{{/imports}}{{/withSeparateModelsAndApi}} +{{#withSeparateModelsAndApi}}{{#hasAllOf}}{{#allOf}} +import { {{class}} } from './{{filename}}';{{/allOf}}{{/hasAllOf}}{{#hasOneOf}}{{#oneOf}} +import { {{class}} } from './{{filename}}';{{/oneOf}}{{/hasOneOf}}{{^hasAllOf}}{{^hasOneOf}}{{#imports}} +import { {{class}} } from './{{filename}}';{{/imports}}{{/hasOneOf}}{{/hasAllOf}}{{/withSeparateModelsAndApi}} {{#models}}{{#model}} -{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{^isEnum}}{{^oneOf}}{{>modelGeneric}}{{/oneOf}}{{/isEnum}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#allOf}}{{#-first}}{{>modelAllOf}}{{/-first}}{{/allOf}}{{^isEnum}}{{^oneOf}}{{^allOf}}{{>modelGeneric}}{{/allOf}}{{/oneOf}}{{/isEnum}} {{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/modelAllOf.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/modelAllOf.mustache new file mode 100644 index 00000000000..0c0dbf9fd89 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-axios/modelAllOf.mustache @@ -0,0 +1,6 @@ +/** + * @type {{classname}}{{#description}} + * {{{description}}}{{/description}} + * @export + */ +export type {{classname}} = {{#allOf}}{{{.}}}{{^-last}} & {{/-last}}{{/allOf}}; diff --git a/modules/openapi-generator/src/main/resources/typescript-redux-query/modelAllOf.mustache b/modules/openapi-generator/src/main/resources/typescript-redux-query/modelAllOf.mustache new file mode 100644 index 00000000000..93eed6a1b07 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-redux-query/modelAllOf.mustache @@ -0,0 +1,36 @@ +{{#hasImports}} +import { + {{#imports}} + {{{.}}}, + {{{.}}}FromJSON, + {{{.}}}ToJSON, + {{/imports}} +} from './'; + +{{/hasImports}} +/** + * @type {{classname}}{{#description}} + * {{{description}}}{{/description}} + * @export + */ +export interface {{classname}} extends {{#allOf}}{{{.}}}{{^-last}}, {{/-last}}{{/allOf}} { +} + +export function {{classname}}FromJSON(json: any): {{classname}} { + return { + {{#allOf}} + ...{{.}}FromJSON(json), + {{/allOf}} + }; +} + +export function {{classname}}ToJSON(value?: {{classname}}): any { + if (value === undefined) { + return undefined; + } + return { + {{#allOf}} + ...{{.}}ToJSON(value), + {{/allOf}} + }; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-redux-query/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/typescript-redux-query/modelOneOf.mustache index 1f6883e78a5..f6dacdd6fdb 100644 --- a/modules/openapi-generator/src/main/resources/typescript-redux-query/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-redux-query/modelOneOf.mustache @@ -34,7 +34,7 @@ export function {{classname}}ToJSON(value?: {{classname}}): any { switch (value.{{propertyName}}) { {{#mappedModels}} - case '{{mappingName}}': return {{modelName}}ToJSON(value); + case '{{mappingName}}': return {{modelName}}ToJSON(<{{modelName}}>value); {{/mappedModels}} default: throw new Error("Unexpected {{propertyName}} value."); } diff --git a/modules/openapi-generator/src/main/resources/typescript-redux-query/models.mustache b/modules/openapi-generator/src/main/resources/typescript-redux-query/models.mustache index bb7d43bce3c..9d541a58da4 100644 --- a/modules/openapi-generator/src/main/resources/typescript-redux-query/models.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-redux-query/models.mustache @@ -11,8 +11,15 @@ {{>modelOneOf}} {{/-first}} {{/oneOf}} +{{#allOf}} +{{#-first}} +{{>modelAllOf}} +{{/-first}} +{{/allOf}} {{^oneOf}} +{{^allOf}} {{>modelGeneric}} +{{/allOf}} {{/oneOf}} {{/isEnum}} {{/model}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientCodegenTest.java new file mode 100644 index 00000000000..1935a3cb95f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientCodegenTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.dartdio; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.DartDioClientCodegen; +import org.openapitools.codegen.languages.DartDioClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class DartDioClientCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final DartDioClientCodegen codegen = new DartDioClientCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final DartDioClientCodegen codegen = new DartDioClientCodegen(); + codegen.setHideGenerationTimestamp(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final DartDioClientCodegen codegen = new DartDioClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); + Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + } + + @Test + public void testKeywords() throws Exception { + final DartDioClientCodegen codegen = new DartDioClientCodegen(); + + List reservedWordsList = new ArrayList(); + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/resources/dart/dart-keywords.txt"), Charset.forName("UTF-8"))); + while(reader.ready()) { reservedWordsList.add(reader.readLine()); } + reader.close(); + } catch (Exception e) { + String errorString = String.format(Locale.ROOT, "Error reading dart keywords: %s", e); + Assert.fail(errorString, e); + } + + Assert.assertEquals(reservedWordsList.size() > 20, true); + Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true); + for(String keyword : reservedWordsList) { + // reserved words are stored in lowercase + Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); + } + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java new file mode 100644 index 00000000000..f59c02ddf48 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioClientOptionsTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.dartdio; + +import mockit.Expectations; +import mockit.Tested; +import org.openapitools.codegen.AbstractOptionsTest; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.languages.DartClientCodegen; +import org.openapitools.codegen.languages.DartDioClientCodegen; +import org.openapitools.codegen.options.DartDioClientOptionsProvider; +import org.openapitools.codegen.options.DartDioClientOptionsProvider; + +public class DartDioClientOptionsTest extends AbstractOptionsTest { + + @Tested + private DartDioClientCodegen clientCodegen; + + public DartDioClientOptionsTest() { + super(new DartDioClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(DartDioClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setBrowserClient(Boolean.valueOf(DartDioClientOptionsProvider.BROWSER_CLIENT_VALUE)); + times = 1; + clientCodegen.setPubName(DartDioClientOptionsProvider.PUB_NAME_VALUE); + times = 1; + clientCodegen.setPubVersion(DartDioClientOptionsProvider.PUB_VERSION_VALUE); + times = 1; + clientCodegen.setPubDescription(DartDioClientOptionsProvider.PUB_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setSourceFolder(DartDioClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setUseEnumExtension(Boolean.valueOf(DartDioClientOptionsProvider.USE_ENUM_EXTENSION)); + times = 1; + clientCodegen.setDateLibrary(DartDioClientOptionsProvider.DATE_LIBRARY); + times = 1; + clientCodegen.setNullableFields(Boolean.valueOf(DartDioClientOptionsProvider.NULLABLE_FIELDS)); + times = 1; + }}; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioModelTest.java new file mode 100644 index 00000000000..1aa56403656 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dartdio/DartDioModelTest.java @@ -0,0 +1,412 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.dartdio; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.DateSchema; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.languages.DartDioClientCodegen; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class DartDioModelTest { + + @Test(description = "convert a simple php model") + public void simpleModelTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema()) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + // {{imports}} is not used in template + //Assert.assertEquals(cm.imports.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertFalse(property1.isContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.dataType, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertFalse(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, "DateTime"); + Assert.assertEquals(property3.dataType, "DateTime"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.baseType, "DateTime"); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isContainer); + } + + @Test(description = "convert a simple dart-dit model with datelibrary") + public void simpleModelWithTimeMachineTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema()) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addProperties("birthDate", new DateSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); + + final DartDioClientCodegen codegen = new DartDioClientCodegen(); + codegen.additionalProperties().put(DartDioClientCodegen.DATE_LIBRARY, "timemachine"); + codegen.setDateLibrary("timemachine"); + codegen.processOpts(); + + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 4); + // {{imports}} is not used in template + //Assert.assertEquals(cm.imports.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertFalse(property1.isContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.dataType, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertFalse(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, "OffsetDateTime"); + Assert.assertEquals(property3.dataType, "OffsetDateTime"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.baseType, "OffsetDateTime"); + Assert.assertTrue(property3.hasMore); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isContainer); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "birthDate"); + Assert.assertEquals(property4.complexType, "LocalDate"); + Assert.assertEquals(property4.dataType, "LocalDate"); + Assert.assertEquals(property4.name, "birthDate"); + Assert.assertEquals(property4.defaultValue, "null"); + Assert.assertEquals(property4.baseType, "LocalDate"); + Assert.assertFalse(property4.hasMore); + Assert.assertFalse(property4.required); + Assert.assertFalse(property4.isContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema()) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertFalse(property1.isContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "BuiltList"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertEquals(property2.baseType, "BuiltList"); + Assert.assertFalse(property2.hasMore); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.dataType, "BuiltMap"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.baseType, "BuiltMap"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertTrue(property1.isPrimitiveType); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new Schema().$ref("#/definitions/Children")); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.dataType, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertFalse(property1.required); + Assert.assertFalse(property1.isContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListProperty() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/definitions/Children"))); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.dataType, "BuiltList"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "BuiltList"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapSchema() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/definitions/Children"))); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + // {{imports}} is not used in template + //Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.dataType, "BuiltMap"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "BuiltMap"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Schema model = new ArraySchema() + .items(new Schema().$ref("#/definitions/Children")) + .description("an array model"); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(model.getDescription(), "an array model"); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertTrue(cm.isArrayModel); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + // skip import test as import is not used by PHP codegen + } + + @Test(description = "convert a map model") + public void mapModelTest() { + final Schema model = new Schema() + .description("a map model") + .additionalProperties(new Schema().$ref("#/definitions/Children")); + final DefaultCodegen codegen = new DartDioClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + // {{imports}} is not used in template + //Assert.assertEquals(cm.imports.size(), 2); + //Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } + + @DataProvider(name = "modelNames") + public static Object[][] primeNumbers() { + return new Object[][] { + {"sample", "Sample"}, + {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, + {"/sample", "Sample"}, + {"\\sample", "\\Sample"}, + {"sample.name", "SampleName"}, + {"_sample", "Sample"}, + }; + } + + @Test(dataProvider = "modelNames", description = "avoid inner class") + public void modelNameTest(String name, String expectedName) { + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema model = new Schema(); + final DefaultCodegen codegen = new DartDioClientCodegen(); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel(name, model); + + Assert.assertEquals(cm.name, name); + Assert.assertEquals(cm.classname, expectedName); + } + + @Test(description = "test enum variable names for reserved words") + public void testReservedWord() throws Exception { + final DefaultCodegen codegen = new DartDioClientCodegen(); + Assert.assertEquals(codegen.toEnumVarName("assert", null), "assert_"); + Assert.assertEquals(codegen.toEnumVarName("default", null), "default_"); + Assert.assertEquals(codegen.toEnumVarName("IF", null), "iF_"); + // should not escape non-reserved + Assert.assertEquals(codegen.toEnumVarName("hello", null), "hello"); + } + + // datetime (or primitive type) not yet supported in HTTP request body + @Test(description = "returns DateTime when using `--model-name-prefix`") + public void dateTest() { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/2_0/datePropertyTest.json"); + final DefaultCodegen codegen = new DartDioClientCodegen(); + codegen.setModelNamePrefix("foo"); + codegen.setOpenAPI(openAPI); + + final String path = "/tests/dateResponse"; + final Operation p = openAPI.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, null); + + Assert.assertEquals(op.returnType, "DateTime"); + Assert.assertEquals(op.bodyParam.dataType, "DateTime"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java index 1febdfe86ee..b80a2fa69d7 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java @@ -416,4 +416,69 @@ public class SpringCodegenTest { codegen.additionalProperties().put(CodegenConstants.LIBRARY, "spring-cloud"); codegen.processOpts(); } + + @Test + public void testDoGenerateRequestBodyRequiredAttribute_3134_Regression() throws Exception { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/3134-regression.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); + + ClientOptInput input = new ClientOptInput(); + input.setOpenAPI(openAPI); + input.setConfig(codegen); + + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(input).generate(); + + checkFileContains(generator, outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java", + "@RequestBody(required = false"); + } + + @Test + public void useBeanValidationTruePerformBeanValidationTrueJava8FalseForFormatEmail() throws IOException { + beanValidationForFormatEmail(true, true, false, "@org.hibernate.validator.constraints.Email", "@javax.validation.constraints.Email"); + } + + @Test + public void useBeanValidationTruePerformBeanValidationFalseJava8TrueForFormatEmail() throws IOException { + beanValidationForFormatEmail(true, false, true, "@javax.validation.constraints.Email", "@org.hibernate.validator.constraints.Email"); + } + + @Test + public void useBeanValidationTruePerformBeanValidationTrueJava8TrueForFormatEmail() throws IOException { + beanValidationForFormatEmail(true, true, true, "@javax.validation.constraints.Email", "@org.hibernate.validator.constraints.Email"); + } + + private void beanValidationForFormatEmail(boolean useBeanValidation, boolean performBeanValidation, boolean java8, String contains, String notContains) throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_4876_format_email.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.setUseBeanValidation(useBeanValidation); + codegen.setPerformBeanValidation(performBeanValidation); + codegen.setJava8(java8); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + MockDefaultGenerator generator = new MockDefaultGenerator(); + generator.opts(input).generate(); + + checkFileContains(generator, outputPath + "/src/main/java/org/openapitools/model/PersonWithEmail.java", contains); + checkFileNotContains(generator, outputPath + "/src/main/java/org/openapitools/model/PersonWithEmail.java", notContains); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java index 2f41cb0925c..d75eb51565a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/BashClientOptionsProvider.java @@ -66,6 +66,7 @@ public class BashClientOptionsProvider implements OptionsProvider { .put(BashClientCodegen.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, "false") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java index 1effb849ece..0ed8360cd61 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartClientOptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class DartClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "true"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String BROWSER_CLIENT_VALUE = "true"; public static final String PUB_NAME_VALUE = "swagger"; @@ -44,6 +45,7 @@ public class DartClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(DartClientCodegen.BROWSER_CLIENT, BROWSER_CLIENT_VALUE) .put(DartClientCodegen.PUB_NAME, PUB_NAME_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java new file mode 100644 index 00000000000..067d0cc4342 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/DartDioClientOptionsProvider.java @@ -0,0 +1,71 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.options; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.DartDioClientCodegen; +import org.openapitools.codegen.languages.DartDioClientCodegen; + +public class DartDioClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "true"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String BROWSER_CLIENT_VALUE = "true"; + public static final String PUB_NAME_VALUE = "swagger"; + public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String PUB_DESCRIPTION_VALUE = "Swagger API client dart"; + public static final String SOURCE_FOLDER_VALUE = "src"; + public static final String USE_ENUM_EXTENSION = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; + public static final String DATE_LIBRARY = "core"; + public static final String NULLABLE_FIELDS = "true"; + + @Override + public String getLanguage() { + return "dart"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(DartDioClientCodegen.BROWSER_CLIENT, BROWSER_CLIENT_VALUE) + .put(DartDioClientCodegen.PUB_NAME, PUB_NAME_VALUE) + .put(DartDioClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) + .put(DartDioClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(DartDioClientCodegen.USE_ENUM_EXTENSION, USE_ENUM_EXTENSION) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) + .put(DartDioClientCodegen.SUPPORT_DART2, "false") + .put(DartDioClientCodegen.DATE_LIBRARY, DATE_LIBRARY) + .put(DartDioClientCodegen.NULLABLE_FIELDS, NULLABLE_FIELDS) + + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java index 9820edbfbf6..2df8fc8b26d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ElixirClientOptionsProvider.java @@ -36,6 +36,7 @@ public class ElixirClientOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, "false") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, "false") .put(CodegenConstants.INVOKER_PACKAGE, "Yay.Pets") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java index 1ff66f0527b..84a228e35ad 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/HaskellServantOptionsProvider.java @@ -27,6 +27,7 @@ public class HaskellServantOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "Model"; public static final String API_PACKAGE_VALUE = "Api"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -42,6 +43,7 @@ public class HaskellServantOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java index 537d9c98374..d0eb8f9e5ca 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpClientOptionsProvider.java @@ -27,6 +27,7 @@ public class PhpClientOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; public static final String INVOKER_PACKAGE_VALUE = "OpenAPITools\\Client\\Php"; @@ -47,6 +48,7 @@ public class PhpClientOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(PhpClientCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java index cb0ce8408b7..26e4c54eb04 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpLumenServerOptionsProvider.java @@ -27,6 +27,7 @@ public class PhpLumenServerOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; public static final String INVOKER_PACKAGE_VALUE = "lumen"; @@ -50,6 +51,7 @@ public class PhpLumenServerOptionsProvider implements OptionsProvider { .put(AbstractPhpCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java index d8f61c084c9..e092073b3b4 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSilexServerOptionsProvider.java @@ -24,6 +24,7 @@ import java.util.Map; public class PhpSilexServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -37,6 +38,7 @@ public class PhpSilexServerOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlim4ServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlim4ServerOptionsProvider.java index 23de2476689..8f3cc49295b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlim4ServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlim4ServerOptionsProvider.java @@ -33,6 +33,7 @@ public class PhpSlim4ServerOptionsProvider implements OptionsProvider { public static final String SRC_BASE_PATH_VALUE = "src"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -54,6 +55,7 @@ public class PhpSlim4ServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java index a7346eb6154..7be804c9d8c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java @@ -32,6 +32,7 @@ public class PhpSlimServerOptionsProvider implements OptionsProvider { public static final String SRC_BASE_PATH_VALUE = "src"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -52,6 +53,7 @@ public class PhpSlimServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java index 61c914163c3..4c11218a844 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java @@ -28,6 +28,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String MODULE_NAME_VALUE = "SwaggerClientRuby"; public static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String GEM_LICENSE_VALUE = "MIT"; public static final String GEM_REQUIRED_RUBY_VERSION_VALUE = ">= 1.9"; @@ -59,6 +60,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { .put(RubyClientCodegen.GEM_AUTHOR, GEM_AUTHOR_VALUE) .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaAkkaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaAkkaClientOptionsProvider.java index f5b93ac3d0c..21bca2b6897 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaAkkaClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaAkkaClientOptionsProvider.java @@ -27,6 +27,7 @@ public class ScalaAkkaClientOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -44,6 +45,7 @@ public class ScalaAkkaClientOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaHttpClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaHttpClientOptionsProvider.java index 37785a56da2..afc42295ec6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaHttpClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaHttpClientOptionsProvider.java @@ -27,11 +27,13 @@ public class ScalaHttpClientOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; + @Override public String getLanguage() { return "scala-http-client"; @@ -43,6 +45,7 @@ public class ScalaHttpClientOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift3OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift3OptionsProvider.java index 9f2f824164e..420f02d8181 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift3OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift3OptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class Swift3OptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String PROJECT_NAME_VALUE = "Swagger"; public static final String RESPONSE_AS_VALUE = "test"; @@ -56,6 +57,7 @@ public class Swift3OptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(Swift3Codegen.PROJECT_NAME, PROJECT_NAME_VALUE) .put(Swift3Codegen.RESPONSE_AS, RESPONSE_AS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift4OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift4OptionsProvider.java index 29692ce08e3..804c23001f2 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift4OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift4OptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class Swift4OptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String PROJECT_NAME_VALUE = "Swagger"; public static final String RESPONSE_AS_VALUE = "test"; @@ -57,6 +58,7 @@ public class Swift4OptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(Swift4Codegen.PROJECT_NAME, PROJECT_NAME_VALUE) .put(Swift4Codegen.RESPONSE_AS, RESPONSE_AS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java index 1797eae8aeb..d21007860a0 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -27,6 +27,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String SUPPORTS_ES6_VALUE = "false"; public static final String STRING_ENUMS_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; private static final String NMP_NAME = "npmName"; @@ -51,6 +52,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java index 9fa344376ee..42f97fcc0fb 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class TypeScriptAngularJsClientOptionsProvider implements OptionsProvider { public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @@ -39,6 +40,7 @@ public class TypeScriptAngularJsClientOptionsProvider implements OptionsProvider public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java index a35a49c7388..db89053f160 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class TypeScriptAureliaClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final Boolean SUPPORTS_ES6_VALUE = false; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @@ -42,6 +43,7 @@ public class TypeScriptAureliaClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java index 03e26a8cff1..2f55682ce42 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -25,6 +25,7 @@ import java.util.Map; public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final Boolean SUPPORTS_ES6_VALUE = false; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @@ -44,6 +45,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java index 290ca147417..995ca1b36bc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -27,6 +27,7 @@ import java.util.Map; public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; public static final String NMP_NAME = "npmName"; @@ -45,6 +46,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java index d85652ee4b2..19d169ae7c8 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java @@ -38,19 +38,19 @@ public class PythonClientExperimentalTest { codegen.setOpenAPI(openAPI); final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", openAPI.getComponents().getSchemas().get("v1beta3.Binding")); Assert.assertEquals(simpleName.name, "v1beta3.Binding"); - Assert.assertEquals(simpleName.classname, "V1beta3Binding"); + Assert.assertEquals(simpleName.classname, "v1beta3_binding.V1beta3Binding"); Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); codegen.setOpenAPI(openAPI); final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", openAPI.getComponents().getSchemas().get("v1beta3.ComponentStatus")); Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); - Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); + Assert.assertEquals(compoundName.classname, "v1beta3_component_status.V1beta3ComponentStatus"); Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; final Operation operation = openAPI.getPaths().get(path).getPost(); final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, null); - Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); + Assert.assertEquals(codegenOperation.returnType, "v1beta3_binding.V1beta3Binding"); Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); } @@ -69,7 +69,7 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", schema); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 3); @@ -117,7 +117,7 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 2); @@ -157,7 +157,7 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); @@ -183,15 +183,15 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.dataType, "Children"); + Assert.assertEquals(property1.dataType, "children.Children"); Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Children"); + Assert.assertEquals(property1.baseType, "children.Children"); Assert.assertFalse(property1.required); Assert.assertFalse(property1.isContainer); } @@ -208,14 +208,14 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.dataType, "[Children]"); + Assert.assertEquals(property1.dataType, "[children.Children]"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "list"); Assert.assertEquals(property1.containerType, "array"); @@ -235,15 +235,15 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("children.Children")).size(), 1); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.dataType, "{str: (Children,)}"); + Assert.assertEquals(property1.dataType, "{str: (children.Children,)}"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "dict"); Assert.assertEquals(property1.containerType, "map"); @@ -265,12 +265,13 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); + Assert.assertEquals(cm.classVarName, "sample"); Assert.assertEquals(cm.description, "an array model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "list"); Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("children.Children")).size(), 1); } // should not start with 'null'. need help from the community to investigate further @@ -285,12 +286,12 @@ public class PythonClientExperimentalTest { final CodegenModel cm = codegen.fromModel("sample", model); Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classname, "sample.Sample"); Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "dict"); Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("children.Children")).size(), 1); } } diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore-with-date-field.yaml b/modules/openapi-generator/src/test/resources/2_0/petstore-with-date-field.yaml new file mode 100644 index 00000000000..3b67970db17 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/petstore-with-date-field.yaml @@ -0,0 +1,688 @@ +swagger: '2.0' +info: + description: 'This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.' + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +schemes: + - http +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/getAll: + get: + tags: + - pet + summary: Get all pets + description: '' + operationId: getAllPets + produces: + - application/xml + - application/json + parameters: + - name: lastUpdated + in: query + description: "When this endpoint was hit last to help indentify if the client already has the latest copy." + required: false + type: "string" + format: "date-time" + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '204': + description: Client already has latest copy of this endpoint + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' + operationId: findPetsByTags + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing.' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header +definitions: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/definitions/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml index a443f059b7e..fa1bdfe009c 100644 --- a/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1238,6 +1238,10 @@ definitions: format: int64 name: type: string + # we added fullName to make sure that serialization/deserialization + # works for a submodel of Pet that also uses js variable names + fullName: + type: string xml: name: Tag Pet: @@ -2038,4 +2042,57 @@ definitions: type: integer xml: namespace: http://g.com/schema - prefix: g \ No newline at end of file + prefix: g + Grandparent: + type: object + properties: + radioWaves: + type: boolean + Parent: + allOf: + - $ref: '#/definitions/Grandparent' + - type: object + properties: + teleVision: + type: boolean + Child: + allOf: + - $ref: '#/definitions/Parent' + - type: object + properties: + interNet: + type: boolean + GrandparentAnimal: + type: object + required: + - pet_type + properties: + pet_type: + type: string + ParentPet: + type: object + allOf: + - $ref: '#/definitions/GrandparentAnimal' + - type: object + discriminator: pet_type + ChildCat: + allOf: + - $ref: '#/definitions/ParentPet' + - type: object + properties: + name: + type: string + ChildDog: + allOf: + - $ref: '#/definitions/ParentPet' + - type: object + properties: + bark: + type: string + ChildLizard: + allOf: + - $ref: '#/definitions/ParentPet' + - type: object + properties: + lovesRocks: + type: boolean \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/3134-regression.yaml b/modules/openapi-generator/src/test/resources/3_0/3134-regression.yaml new file mode 100644 index 00000000000..a9fc8fb4532 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/3134-regression.yaml @@ -0,0 +1,23 @@ +openapi: 3.0.2 +info: + title: info + description: info + version: 0.1.0 + +paths: + /example/api: + post: + summary: summary + description: description + requestBody: + required: false + content: + application/json: + schema: + type: object + properties: + name: + type: string + responses: + 200: + description: response \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_4876_format_email.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_4876_format_email.yaml new file mode 100644 index 00000000000..053f62ebdf5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_4876_format_email.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + version: 1.0.0 + title: EmailExample + license: + name: MIT +servers: + - url: http://api.example.xyz/v1 +paths: + /person: + put: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/personWithEmail' + responses: + '204': + description: No Content +components: + schemas: + personWithEmail: + properties: + name: + type: string + maxLength: 255 + email: + type: string + format: email diff --git a/pom.xml b/pom.xml index ff76fc26b28..f1bf09338b7 100644 --- a/pom.xml +++ b/pom.xml @@ -1048,6 +1048,7 @@ samples/client/petstore/php/OpenAPIClient-php samples/openapi3/client/petstore/php/OpenAPIClient-php samples/server/petstore/php-slim + samples/server/petstore/php-slim4 samples/client/petstore/javascript samples/client/petstore/javascript-es6 samples/openapi3/client/petstore/javascript-es6 @@ -1078,7 +1079,7 @@ samples/client/petstore/typescript-angular-v7-provided-in-root samples/server/petstore/rust-server samples/server/petstore/python-flask - samples/server/petstore/python-flask-python2 + @@ -1254,9 +1255,12 @@ samples/client/petstore/kotlin/ samples/client/petstore/kotlin-gson/ samples/client/petstore/kotlin-nonpublic/ + samples/client/petstore/kotlin-nullable/ samples/client/petstore/kotlin-okhttp3/ samples/client/petstore/kotlin-threetenbp/ samples/client/petstore/kotlin-string/ + samples/client/petstore/kotlin-moshi-codegen/ + samples/client/petstore/kotlin-json-request-date/ samples/server/petstore/erlang-server samples/server/petstore/jaxrs/jersey2 diff --git a/samples/client/petstore/R/.Rbuildignore b/samples/client/petstore/R/.Rbuildignore index 5b6417737e6..d2835cda099 100644 --- a/samples/client/petstore/R/.Rbuildignore +++ b/samples/client/petstore/R/.Rbuildignore @@ -3,3 +3,5 @@ ^\.openapi-generator-ignore$ ^\.travis\.yml$ ^\.openapi-generator$ +^docs$ +^git_push\.sh$ \ No newline at end of file diff --git a/samples/client/petstore/R/DESCRIPTION b/samples/client/petstore/R/DESCRIPTION index a1174eda1f2..3f8ad457487 100644 --- a/samples/client/petstore/R/DESCRIPTION +++ b/samples/client/petstore/R/DESCRIPTION @@ -3,7 +3,7 @@ Title: R Package Client for OpenAPI Petstore Version: 1.0.0 Authors@R: person("OpenAPI Generator community", email = "team@openapitools.org", role = c("aut", "cre")) Description: This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -Depends: R (>= 3.3.3) +Depends: R (>= 3.3) Encoding: UTF-8 License: Apache-2.0 LazyData: true diff --git a/samples/client/petstore/dart-dio/.gitignore b/samples/client/petstore/dart-dio/.gitignore index 7c280441649..8092a49d515 100644 --- a/samples/client/petstore/dart-dio/.gitignore +++ b/samples/client/petstore/dart-dio/.gitignore @@ -1,6 +1,7 @@ -# See https://www.dartlang.org/tools/private-files.html +# See https://dart.dev/guides/libraries/private-files # Files and directories created by pub +.dart_tool/ .buildlog .packages .project @@ -25,3 +26,12 @@ doc/api/ # Don't commit pubspec lock file # (Library packages only! Remove pattern if developing an application package) pubspec.lock + +# Don’t commit files and directories created by other development environments. +# For example, if your development environment creates any of the following files, +# consider putting them in a global ignore file: +*.iml // IntelliJ +*.ipr // IntelliJ +*.iws // IntelliJ +.idea/ // IntelliJ +.DS_Store // Mac diff --git a/samples/client/petstore/dart2/openapi/.openapi-generator/VERSION b/samples/client/petstore/dart2/openapi/.openapi-generator/VERSION index bfbf77eb7fa..b93d1c64408 100644 --- a/samples/client/petstore/dart2/openapi/.openapi-generator/VERSION +++ b/samples/client/petstore/dart2/openapi/.openapi-generator/VERSION @@ -1 +1,5 @@ -4.3.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +4.3.0-SNAPSHOT +======= +4.2.3-SNAPSHOT +>>>>>>> origin/master diff --git a/samples/client/petstore/go-experimental/go-petstore/README.md b/samples/client/petstore/go-experimental/go-petstore/README.md index b976d6549d5..a39c8c25075 100644 --- a/samples/client/petstore/go-experimental/go-petstore/README.md +++ b/samples/client/petstore/go-experimental/go-petstore/README.md @@ -26,6 +26,47 @@ Put the package under your project folder and add the following in import: import sw "./petstore" ``` +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + ## Documentation for API Endpoints All URIs are relative to *http://petstore.swagger.io:80/v2* diff --git a/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go b/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go index 44a84210ab2..f5e420b84fa 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go @@ -41,8 +41,13 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, bod localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/another-fake/dummy" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "AnotherFakeApiService.Call123TestSpecialTags") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/another-fake/dummy" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake.go b/samples/client/petstore/go-experimental/go-petstore/api_fake.go index 8c0e6c80221..d31e1b9139c 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake.go @@ -42,8 +42,13 @@ func (a *FakeApiService) CreateXmlItem(ctx _context.Context, xmlItem XmlItem) (* localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/create_xml_item" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.CreateXmlItem") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/create_xml_item" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -117,8 +122,13 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa localVarReturnValue bool ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/boolean" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterBooleanSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/boolean" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -213,8 +223,13 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local localVarReturnValue OuterComposite ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/composite" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterCompositeSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/composite" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -313,8 +328,13 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar localVarReturnValue float32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/number" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterNumberSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/number" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -409,8 +429,13 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar localVarReturnValue string ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/string" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterStringSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/string" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -497,8 +522,13 @@ func (a *FakeApiService) TestBodyWithFileSchema(ctx _context.Context, body FileS localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/body-with-file-schema" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithFileSchema") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/body-with-file-schema" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -564,8 +594,13 @@ func (a *FakeApiService) TestBodyWithQueryParams(ctx _context.Context, query str localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/body-with-query-params" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithQueryParams") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/body-with-query-params" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -634,8 +669,13 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, body Client) (Cli localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestClientModel") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -747,8 +787,13 @@ func (a *FakeApiService) TestEndpointParameters(ctx _context.Context, number flo localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEndpointParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -890,8 +935,13 @@ func (a *FakeApiService) TestEnumParameters(ctx _context.Context, localVarOption localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEnumParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -992,8 +1042,13 @@ func (a *FakeApiService) TestGroupParameters(ctx _context.Context, requiredStrin localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestGroupParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -1068,8 +1123,13 @@ func (a *FakeApiService) TestInlineAdditionalProperties(ctx _context.Context, pa localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/inline-additionalProperties" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestInlineAdditionalProperties") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/inline-additionalProperties" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -1135,8 +1195,13 @@ func (a *FakeApiService) TestJsonFormData(ctx _context.Context, param string, pa localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/jsonFormData" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestJsonFormData") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/jsonFormData" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -1206,8 +1271,13 @@ func (a *FakeApiService) TestQueryParameterCollectionFormat(ctx _context.Context localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/test-query-paramters" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestQueryParameterCollectionFormat") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/test-query-paramters" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index 797ba66be5d..ef129021d82 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -41,8 +41,13 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, bod localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake_classname_test" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeClassnameTags123ApiService.TestClassname") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake_classname_test" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} diff --git a/samples/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/client/petstore/go-experimental/go-petstore/api_pet.go index 97fcce49e6f..9b397dabb97 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_pet.go @@ -41,8 +41,13 @@ func (a *PetApiService) AddPet(ctx _context.Context, body Pet) (*_nethttp.Respon localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.AddPet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -114,8 +119,12 @@ func (a *PetApiService) DeletePet(ctx _context.Context, petId int64, localVarOpt localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.DeletePet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -186,8 +195,13 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) localVarReturnValue []Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/findByStatus" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByStatus") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/findByStatus" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -240,7 +254,6 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -274,8 +287,13 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P localVarReturnValue []Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/findByTags" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByTags") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/findByTags" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -328,7 +346,6 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -362,8 +379,12 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne localVarReturnValue Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.GetPetById") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -431,7 +452,6 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -462,8 +482,13 @@ func (a *PetApiService) UpdatePet(ctx _context.Context, body Pet) (*_nethttp.Res localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -537,8 +562,12 @@ func (a *PetApiService) UpdatePetWithForm(ctx _context.Context, petId int64, loc localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePetWithForm") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -620,8 +649,12 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp localVarReturnValue ApiResponse ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}/uploadImage" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFile") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}/uploadImage" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -732,8 +765,12 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i localVarReturnValue ApiResponse ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/{petId}/uploadImageWithRequiredFile" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFileWithRequiredFile") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/{petId}/uploadImageWithRequiredFile" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) diff --git a/samples/client/petstore/go-experimental/go-petstore/api_store.go b/samples/client/petstore/go-experimental/go-petstore/api_store.go index 124da027994..12047d17357 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_store.go @@ -40,8 +40,12 @@ func (a *StoreApiService) DeleteOrder(ctx _context.Context, orderId string) (*_n localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.DeleteOrder") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order/{order_id}" localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -108,8 +112,13 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32, localVarReturnValue map[string]int32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/inventory" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetInventory") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/inventory" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -207,8 +216,12 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord localVarReturnValue Order ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetOrderById") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order/{order_id}" localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -268,7 +281,6 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -301,8 +313,13 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, body Order) (Order, * localVarReturnValue Order ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.PlaceOrder") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -356,7 +373,6 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, body Order) (Order, * } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_user.go b/samples/client/petstore/go-experimental/go-petstore/api_user.go index a1cdb4586d3..5689de23b63 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_user.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_user.go @@ -40,8 +40,13 @@ func (a *UserApiService) CreateUser(ctx _context.Context, body User) (*_nethttp. localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -106,8 +111,13 @@ func (a *UserApiService) CreateUsersWithArrayInput(ctx _context.Context, body [] localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/createWithArray" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithArrayInput") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/createWithArray" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -172,8 +182,13 @@ func (a *UserApiService) CreateUsersWithListInput(ctx _context.Context, body []U localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/createWithList" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithListInput") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/createWithList" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -239,8 +254,12 @@ func (a *UserApiService) DeleteUser(ctx _context.Context, username string) (*_ne localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.DeleteUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -307,8 +326,12 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U localVarReturnValue User ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.GetUserByName") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) @@ -362,7 +385,6 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -396,8 +418,13 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo localVarReturnValue string ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/login" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LoginUser") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/login" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -451,7 +478,6 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -481,8 +507,13 @@ func (a *UserApiService) LogoutUser(ctx _context.Context) (*_nethttp.Response, e localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/logout" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LogoutUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/logout" + localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} @@ -547,8 +578,12 @@ func (a *UserApiService) UpdateUser(ctx _context.Context, username string, body localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.UpdateUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) diff --git a/samples/client/petstore/go-experimental/go-petstore/client.go b/samples/client/petstore/go-experimental/go-petstore/client.go index 99adfbca747..4c4ecf168f4 100644 --- a/samples/client/petstore/go-experimental/go-petstore/client.go +++ b/samples/client/petstore/go-experimental/go-petstore/client.go @@ -197,11 +197,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return resp, err } -// ChangeBasePath changes base path to allow switching to mocks -func (c *APIClient) ChangeBasePath(path string) { - c.cfg.BasePath = path -} - // Allow modification of underlying config for alternate implementations and testing // Caution: modifying the configuration while live can cause data races and potentially unwanted behavior func (c *APIClient) GetConfig() *Configuration { diff --git a/samples/client/petstore/go-experimental/go-petstore/configuration.go b/samples/client/petstore/go-experimental/go-petstore/configuration.go index 5a4a915d1d3..9c5a196fc3b 100644 --- a/samples/client/petstore/go-experimental/go-petstore/configuration.go +++ b/samples/client/petstore/go-experimental/go-petstore/configuration.go @@ -10,6 +10,7 @@ package petstore import ( + "context" "fmt" "net/http" "strings" @@ -37,6 +38,18 @@ var ( // ContextAPIKeys takes a string apikey as authentication for the request ContextAPIKeys = contextKey("apiKeys") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth @@ -60,35 +73,40 @@ type ServerVariable struct { // ServerConfiguration stores the information about a server type ServerConfiguration struct { - Url string + URL string Description string Variables map[string]ServerVariable } +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + // Configuration stores the configuration of the API client type Configuration struct { - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - Debug bool `json:"debug,omitempty"` - Servers []ServerConfiguration - HTTPClient *http.Client + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client } // NewConfiguration returns a new Configuration object func NewConfiguration() *Configuration { cfg := &Configuration{ - BasePath: "http://petstore.swagger.io:80/v2", - DefaultHeader: make(map[string]string), - UserAgent: "OpenAPI-Generator/1.0.0/go", - Debug: false, - Servers: []ServerConfiguration{{ - Url: "http://petstore.swagger.io:80/v2", + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://petstore.swagger.io:80/v2", Description: "No description provided", }, }, + OperationServers: map[string]ServerConfigurations{ + }, } return cfg } @@ -98,13 +116,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } -// ServerUrl returns URL based on server settings -func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) { - if index < 0 || len(c.Servers) <= index { - return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1) +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) } - server := c.Servers[index] - url := server.Url + server := sc[index] + url := server.URL // go through variables and replace placeholders for name, variable := range server.Variables { @@ -125,3 +143,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin } return url, nil } + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/client/petstore/go-experimental/go-petstore/model_200_response.go b/samples/client/petstore/go-experimental/go-petstore/model_200_response.go index 6aa7f9b6a79..b4e9becc59c 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_200_response.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_200_response.go @@ -97,7 +97,7 @@ func (v NullableModel200Response) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableModel200Response) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableModel200Response) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_any_type.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_any_type.go index c6fbcc703b3..72a28831595 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_any_type.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_any_type.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesAnyType) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesAnyType) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesAnyType) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_array.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_array.go index b1bf7f33282..1a20f680cb9 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_array.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_array.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesArray) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesArray) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesArray) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_boolean.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_boolean.go index c1aacbc1eb5..218547d406c 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_boolean.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_boolean.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesBoolean) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesBoolean) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesBoolean) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go index 3c1e8db6244..1a9c27fbd66 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go @@ -403,7 +403,7 @@ func (v NullableAdditionalPropertiesClass) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { @@ -414,4 +414,3 @@ func (v *NullableAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_integer.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_integer.go index 07c11d9cdcd..40e13711d00 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_integer.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_integer.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesInteger) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesInteger) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesInteger) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_number.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_number.go index 59759fb409e..36cd75cd687 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_number.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_number.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesNumber) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesNumber) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesNumber) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_object.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_object.go index df2b0305a4d..3b284106f61 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_object.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_object.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesObject) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesObject) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesObject) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_string.go b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_string.go index 47eb4dd0de5..c0e754757bd 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_string.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_additional_properties_string.go @@ -63,7 +63,7 @@ func (v NullableAdditionalPropertiesString) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesString) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableAdditionalPropertiesString) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_animal.go b/samples/client/petstore/go-experimental/go-petstore/model_animal.go index dfae59606ed..b54f59dbe61 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_animal.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_animal.go @@ -79,7 +79,7 @@ func (v NullableAnimal) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAnimal) UnmarshalJSON(src []byte) error { @@ -90,4 +90,3 @@ func (v *NullableAnimal) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_api_response.go b/samples/client/petstore/go-experimental/go-petstore/model_api_response.go index e2d80e22074..0b9eab9f759 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_api_response.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_api_response.go @@ -131,7 +131,7 @@ func (v NullableApiResponse) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableApiResponse) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableApiResponse) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go b/samples/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go index cf5e59622f3..f2dbbb1f21e 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go @@ -63,7 +63,7 @@ func (v NullableArrayOfArrayOfNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayOfArrayOfNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableArrayOfArrayOfNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go b/samples/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go index 7495577a4ce..9268a2ae608 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go @@ -63,7 +63,7 @@ func (v NullableArrayOfNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayOfNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableArrayOfNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_array_test_.go b/samples/client/petstore/go-experimental/go-petstore/model_array_test_.go index 01d310fd480..84123ef137b 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_array_test_.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_array_test_.go @@ -131,7 +131,7 @@ func (v NullableArrayTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayTest) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableArrayTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_capitalization.go b/samples/client/petstore/go-experimental/go-petstore/model_capitalization.go index 281f380508c..8288d903b7b 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_capitalization.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_capitalization.go @@ -234,7 +234,7 @@ func (v NullableCapitalization) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCapitalization) UnmarshalJSON(src []byte) error { @@ -245,4 +245,3 @@ func (v *NullableCapitalization) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_cat.go b/samples/client/petstore/go-experimental/go-petstore/model_cat.go index a4390348e39..a9f83cc8c40 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_cat.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_cat.go @@ -113,7 +113,7 @@ func (v NullableCat) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCat) UnmarshalJSON(src []byte) error { @@ -124,4 +124,3 @@ func (v *NullableCat) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_cat_all_of.go b/samples/client/petstore/go-experimental/go-petstore/model_cat_all_of.go index 5fe06820a25..60ba5b0259f 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_cat_all_of.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_cat_all_of.go @@ -63,7 +63,7 @@ func (v NullableCatAllOf) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCatAllOf) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableCatAllOf) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_category.go b/samples/client/petstore/go-experimental/go-petstore/model_category.go index 1a4d80c25ab..0bf8c0a2fd2 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_category.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_category.go @@ -79,7 +79,7 @@ func (v NullableCategory) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCategory) UnmarshalJSON(src []byte) error { @@ -90,4 +90,3 @@ func (v *NullableCategory) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_class_model.go b/samples/client/petstore/go-experimental/go-petstore/model_class_model.go index cb217ea0b93..1621fc4acbd 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_class_model.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_class_model.go @@ -63,7 +63,7 @@ func (v NullableClassModel) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableClassModel) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableClassModel) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_client.go b/samples/client/petstore/go-experimental/go-petstore/model_client.go index 1c2d82dbaa2..45f3fce18b4 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_client.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_client.go @@ -63,7 +63,7 @@ func (v NullableClient) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableClient) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableClient) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_dog.go b/samples/client/petstore/go-experimental/go-petstore/model_dog.go index 1e12cf2030e..eb2d7f05d41 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_dog.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_dog.go @@ -113,7 +113,7 @@ func (v NullableDog) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableDog) UnmarshalJSON(src []byte) error { @@ -124,4 +124,3 @@ func (v *NullableDog) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_dog_all_of.go b/samples/client/petstore/go-experimental/go-petstore/model_dog_all_of.go index 0572953d469..c88dfaca2e0 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_dog_all_of.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_dog_all_of.go @@ -63,7 +63,7 @@ func (v NullableDogAllOf) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableDogAllOf) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableDogAllOf) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_enum_arrays.go b/samples/client/petstore/go-experimental/go-petstore/model_enum_arrays.go index 68b520550b3..181a9287220 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_enum_arrays.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_enum_arrays.go @@ -97,7 +97,7 @@ func (v NullableEnumArrays) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumArrays) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableEnumArrays) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_enum_class.go b/samples/client/petstore/go-experimental/go-petstore/model_enum_class.go index 8864dc38698..4311401eac6 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_enum_class.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_enum_class.go @@ -31,13 +31,11 @@ type NullableEnumClass struct { func (v NullableEnumClass) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumClass) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableEnumClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_enum_test_.go b/samples/client/petstore/go-experimental/go-petstore/model_enum_test_.go index 8594082a56a..c774c9b8f4f 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_enum_test_.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_enum_test_.go @@ -181,7 +181,7 @@ func (v NullableEnumTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumTest) UnmarshalJSON(src []byte) error { @@ -192,4 +192,3 @@ func (v *NullableEnumTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_file.go b/samples/client/petstore/go-experimental/go-petstore/model_file.go index d35f12c0887..23da628abcc 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_file.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_file.go @@ -64,7 +64,7 @@ func (v NullableFile) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFile) UnmarshalJSON(src []byte) error { @@ -75,4 +75,3 @@ func (v *NullableFile) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go b/samples/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go index 5c6a45436be..50145af1223 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go @@ -97,7 +97,7 @@ func (v NullableFileSchemaTestClass) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFileSchemaTestClass) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableFileSchemaTestClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_format_test_.go b/samples/client/petstore/go-experimental/go-petstore/model_format_test_.go index 6676cf826fb..608a083d7eb 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_format_test_.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_format_test_.go @@ -435,7 +435,7 @@ func (v NullableFormatTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFormatTest) UnmarshalJSON(src []byte) error { @@ -446,4 +446,3 @@ func (v *NullableFormatTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go b/samples/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go index 4d6a4ade3ba..5394aa4007d 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go @@ -97,7 +97,7 @@ func (v NullableHasOnlyReadOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableHasOnlyReadOnly) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableHasOnlyReadOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_list.go b/samples/client/petstore/go-experimental/go-petstore/model_list.go index 2e341b13fe2..6259d7507a3 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_list.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_list.go @@ -63,7 +63,7 @@ func (v NullableList) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableList) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableList) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_map_test_.go b/samples/client/petstore/go-experimental/go-petstore/model_map_test_.go index 482e2dcaa54..820f2641347 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_map_test_.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_map_test_.go @@ -165,7 +165,7 @@ func (v NullableMapTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableMapTest) UnmarshalJSON(src []byte) error { @@ -176,4 +176,3 @@ func (v *NullableMapTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go b/samples/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go index 29a15dd4b9b..c4a7dba8182 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go @@ -132,7 +132,7 @@ func (v NullableMixedPropertiesAndAdditionalPropertiesClass) MarshalJSON() ([]by return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableMixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { @@ -143,4 +143,3 @@ func (v *NullableMixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(src return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_name.go b/samples/client/petstore/go-experimental/go-petstore/model_name.go index 15cb31cf79f..2f3716aad24 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_name.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_name.go @@ -147,7 +147,7 @@ func (v NullableName) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableName) UnmarshalJSON(src []byte) error { @@ -158,4 +158,3 @@ func (v *NullableName) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_number_only.go b/samples/client/petstore/go-experimental/go-petstore/model_number_only.go index a844fb8128a..afa9c1b403a 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_number_only.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_number_only.go @@ -63,7 +63,7 @@ func (v NullableNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_order.go b/samples/client/petstore/go-experimental/go-petstore/model_order.go index d138fa95cba..448d6a975a4 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_order.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_order.go @@ -235,7 +235,7 @@ func (v NullableOrder) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOrder) UnmarshalJSON(src []byte) error { @@ -246,4 +246,3 @@ func (v *NullableOrder) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_outer_composite.go b/samples/client/petstore/go-experimental/go-petstore/model_outer_composite.go index b22599eb672..423d3e5ad37 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_outer_composite.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_outer_composite.go @@ -131,7 +131,7 @@ func (v NullableOuterComposite) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterComposite) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableOuterComposite) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_outer_enum.go b/samples/client/petstore/go-experimental/go-petstore/model_outer_enum.go index b6385fcb563..c2a75fee846 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_outer_enum.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_outer_enum.go @@ -31,13 +31,11 @@ type NullableOuterEnum struct { func (v NullableOuterEnum) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterEnum) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableOuterEnum) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_pet.go b/samples/client/petstore/go-experimental/go-petstore/model_pet.go index 405a179218b..7c1228c8b61 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_pet.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_pet.go @@ -198,7 +198,7 @@ func (v NullablePet) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullablePet) UnmarshalJSON(src []byte) error { @@ -209,4 +209,3 @@ func (v *NullablePet) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_read_only_first.go b/samples/client/petstore/go-experimental/go-petstore/model_read_only_first.go index bdd9807ca89..424ef8b81f3 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_read_only_first.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_read_only_first.go @@ -97,7 +97,7 @@ func (v NullableReadOnlyFirst) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableReadOnlyFirst) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableReadOnlyFirst) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_return.go b/samples/client/petstore/go-experimental/go-petstore/model_return.go index 14821a5ca74..785303c992d 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_return.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_return.go @@ -63,7 +63,7 @@ func (v NullableReturn) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableReturn) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableReturn) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_special_model_name.go b/samples/client/petstore/go-experimental/go-petstore/model_special_model_name.go index abafacb4e4d..e1827cee896 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_special_model_name.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_special_model_name.go @@ -63,7 +63,7 @@ func (v NullableSpecialModelName) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableSpecialModelName) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableSpecialModelName) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_tag.go b/samples/client/petstore/go-experimental/go-petstore/model_tag.go index a702f37f093..bcb30265ab2 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_tag.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_tag.go @@ -97,7 +97,7 @@ func (v NullableTag) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableTag) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableTag) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_type_holder_default.go b/samples/client/petstore/go-experimental/go-petstore/model_type_holder_default.go index 173bd1c1b98..e57edcc4aa6 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_type_holder_default.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_type_holder_default.go @@ -109,7 +109,7 @@ func (v NullableTypeHolderDefault) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableTypeHolderDefault) UnmarshalJSON(src []byte) error { @@ -120,4 +120,3 @@ func (v *NullableTypeHolderDefault) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_type_holder_example.go b/samples/client/petstore/go-experimental/go-petstore/model_type_holder_example.go index 6cd9a0867ca..3837bcdbb60 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_type_holder_example.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_type_holder_example.go @@ -125,7 +125,7 @@ func (v NullableTypeHolderExample) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableTypeHolderExample) UnmarshalJSON(src []byte) error { @@ -136,4 +136,3 @@ func (v *NullableTypeHolderExample) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_user.go b/samples/client/petstore/go-experimental/go-petstore/model_user.go index 4411c284794..a427f7f7c24 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_user.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_user.go @@ -302,7 +302,7 @@ func (v NullableUser) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableUser) UnmarshalJSON(src []byte) error { @@ -313,4 +313,3 @@ func (v *NullableUser) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/go-experimental/go-petstore/model_xml_item.go b/samples/client/petstore/go-experimental/go-petstore/model_xml_item.go index ddf16b84247..6f81fca2b94 100644 --- a/samples/client/petstore/go-experimental/go-petstore/model_xml_item.go +++ b/samples/client/petstore/go-experimental/go-petstore/model_xml_item.go @@ -1015,7 +1015,7 @@ func (v NullableXmlItem) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableXmlItem) UnmarshalJSON(src []byte) error { @@ -1026,4 +1026,3 @@ func (v *NullableXmlItem) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/client/petstore/kotlin-gson/build.gradle b/samples/client/petstore/kotlin-gson/build.gradle index 2b975060242..f433e626ce3 100644 --- a/samples/client/petstore/kotlin-gson/build.gradle +++ b/samples/client/petstore/kotlin-gson/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() diff --git a/samples/client/petstore/kotlin-gson/docs/Pet.md b/samples/client/petstore/kotlin-gson/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-gson/docs/Pet.md +++ b/samples/client/petstore/kotlin-gson/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 5eabd2dbcb4..1638d460c68 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 8f24aeabaaf..18355b552ae 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index db099377b83..4f18a92d223 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index b397f322247..85289406926 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index a81be094f41..0461f8a47e9 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -9,11 +9,14 @@ import java.util.Date object Serializer { @JvmStatic - val gson: Gson = GsonBuilder() + val gsonBuilder: GsonBuilder = GsonBuilder() .registerTypeAdapter(Date::class.java, DateAdapter()) .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) - .registerTypeAdapter(UUID::class.java, UUIDAdapter()) .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) - .create() + + @JvmStatic + val gson: Gson by lazy { + gsonBuilder.create() + } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt deleted file mode 100644 index 04dce98308e..00000000000 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ /dev/null @@ -1,34 +0,0 @@ -package org.openapitools.client.infrastructure - -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -import java.util.UUID - -class UUIDAdapter : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: UUID?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(value.toString()) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): UUID? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return UUID.fromString(out.nextString()) - } - } - } -} diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt index c9c7e0d8f1e..9a500cc7037 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -17,10 +17,10 @@ import org.openapitools.client.models.Tag import com.google.gson.annotations.SerializedName /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin-json-request-date/.openapi-generator-ignore b/samples/client/petstore/kotlin-json-request-date/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/.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/petstore/kotlin-json-request-date/.openapi-generator/VERSION b/samples/client/petstore/kotlin-json-request-date/.openapi-generator/VERSION new file mode 100644 index 00000000000..58592f031f6 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/README.md b/samples/client/petstore/kotlin-json-request-date/README.md new file mode 100644 index 00000000000..9e9c5a2326b --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/README.md @@ -0,0 +1,90 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +## Requires + +* Kotlin 1.3.41 +* Gradle 4.9 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getAllPets**](docs/PetApi.md#getallpets) | **GET** /pet/getAll | Get all pets +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.ApiResponse](docs/ApiResponse.md) + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/kotlin-json-request-date/build.gradle b/samples/client/petstore/kotlin-json-request-date/build.gradle new file mode 100644 index 00000000000..ed72aa19d9e --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/build.gradle @@ -0,0 +1,37 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.61' + + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' + +repositories { + mavenCentral() +} + +test { + useJUnitPlatform() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" + compile "com.squareup.okhttp3:okhttp:4.2.2" + testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" +} diff --git a/samples/client/petstore/kotlin-json-request-date/docs/ApiResponse.md b/samples/client/petstore/kotlin-json-request-date/docs/ApiResponse.md new file mode 100644 index 00000000000..6b4c6bf2779 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/Category.md b/samples/client/petstore/kotlin-json-request-date/docs/Category.md new file mode 100644 index 00000000000..2c28a670fc7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/Order.md b/samples/client/petstore/kotlin-json-request-date/docs/Order.md new file mode 100644 index 00000000000..ef31dbf2f4f --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**java.time.LocalDateTime**](java.time.LocalDateTime.md) | | [optional] +**status** | [**inline**](#StatusEnum) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/Pet.md b/samples/client/petstore/kotlin-json-request-date/docs/Pet.md new file mode 100644 index 00000000000..70c340005d1 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/PetApi.md b/samples/client/petstore/kotlin-json-request-date/docs/PetApi.md new file mode 100644 index 00000000000..f3b19f26edb --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/PetApi.md @@ -0,0 +1,403 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getAllPets**](PetApi.md#getAllPets) | **GET** /pet/getAll | Get all pets +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByTags** +> kotlin.Array<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.Array = // kotlin.Array | Tags to filter by +try { + val result : kotlin.Array = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.Array<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getAllPets** +> kotlin.Array<Pet> getAllPets(lastUpdated) + +Get all pets + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val lastUpdated : java.time.LocalDateTime = 2013-10-20T19:20:30+01:00 // java.time.LocalDateTime | When this endpoint was hit last to help indentify if the client already has the latest copy. +try { + val result : kotlin.Array = apiInstance.getAllPets(lastUpdated) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getAllPets") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getAllPets") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **lastUpdated** | **java.time.LocalDateTime**| When this endpoint was hit last to help indentify if the client already has the latest copy. | [optional] + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload +try { + val result : ApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/StoreApi.md b/samples/client/petstore/kotlin-json-request-date/docs/StoreApi.md new file mode 100644 index 00000000000..f4986041af8 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/StoreApi.md @@ -0,0 +1,196 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val body : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(body) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/Tag.md b/samples/client/petstore/kotlin-json-request-date/docs/Tag.md new file mode 100644 index 00000000000..60ce1bcdbad --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/User.md b/samples/client/petstore/kotlin-json-request-date/docs/User.md new file mode 100644 index 00000000000..e801729b5ed --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-json-request-date/docs/UserApi.md b/samples/client/petstore/kotlin-json-request-date/docs/UserApi.md new file mode 100644 index 00000000000..0f55f06bc62 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : User = // User | Created user object +try { + apiInstance.createUser(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithArrayInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithListInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val body : User = // User | Updated user object +try { + apiInstance.updateUser(username, body) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-json-request-date/pom.xml b/samples/client/petstore/kotlin-json-request-date/pom.xml new file mode 100644 index 00000000000..27124bdb901 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + io.swagger + KotlinJsonRequestDateClientTests + pom + 1.0-SNAPSHOT + Kotlin Moshi Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-test + integration-test + + exec + + + gradle + + test + + + + + + + + diff --git a/samples/client/petstore/kotlin-json-request-date/settings.gradle b/samples/client/petstore/kotlin-json-request-date/settings.gradle new file mode 100644 index 00000000000..6dde48f7256 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-json-request-date' \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..3f70f1a2e20 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,368 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.ApiResponse +import org.openapitools.client.models.Pet + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun addPet(body: Pet) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("api_key" to apiKey.toString()) + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return kotlin.Array + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun findPetsByTags(tags: kotlin.Array) : kotlin.Array { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("tags", toMultiValue(tags.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/findByTags", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Get all pets + * + * @param lastUpdated When this endpoint was hit last to help indentify if the client already has the latest copy. (optional) + * @return kotlin.Array + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getAllPets(lastUpdated: java.time.LocalDateTime?) : kotlin.Array { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (lastUpdated != null) { + put("lastUpdated", listOf(parseDateToQueryString(lastUpdated))) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/getAll", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return Pet + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getPetById(petId: kotlin.Long) : Pet { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Pet + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePet(body: Pet) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { + val localVariableBody: kotlin.Any? = mapOf("name" to "$name", "status" to "$status") + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "") + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { + val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to "$additionalMetadata", "file" to "$file") + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "") + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..18355b552ae --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,192 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.Order + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteOrder(orderId: kotlin.String) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return kotlin.collections.Map + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getInventory() : kotlin.collections.Map { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/inventory", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getOrderById(orderId: kotlin.Long) : Order { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun placeOrder(body: Order) : Order { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/store/order", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..4f18a92d223 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,357 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.User + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUser(body: User) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithArrayInput(body: kotlin.Array) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithArray", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithListInput(body: kotlin.Array) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithList", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteUser(username: kotlin.String) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getUserByName(username: kotlin.String) : User { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return kotlin.String + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("username", listOf(username.toString())) + put("password", listOf(password.toString())) + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/login", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Logs out current logged in user session + * + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun logoutUser() : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/logout", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updateUser(username: kotlin.String, body: User) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..5670d3c132b --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,183 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Credentials +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.FormBody +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.ResponseBody +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.Request +import java.io.File + +open class ApiClient(val baseUrl: String) { + companion object { + protected const val ContentType = "Content-Type" + protected const val Accept = "Accept" + protected const val Authorization = "Authorization" + protected const val JsonMediaType = "application/json" + protected const val FormDataMediaType = "multipart/form-data" + protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded" + protected const val XmlMediaType = "application/xml" + + val apiKey: MutableMap = mutableMapOf() + val apiKeyPrefix: MutableMap = mutableMapOf() + var username: String? = null + var password: String? = null + var accessToken: String? = null + + @JvmStatic + val client: OkHttpClient by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType || mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, value) + } + }.build() + } + mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") + // TODO: this should be extended with other serializers + else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") + } + + protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { + if(body == null) { + return null + } + val bodyContent = body.string() + if (bodyContent.isEmpty()) { + return null + } + return when(mediaType) { + JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) + else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") + } + } + + protected fun updateAuthParams(requestConfig: RequestConfig) { + if (requestConfig.headers["api_key"].isNullOrEmpty()) { + if (apiKey["api_key"] != null) { + if (apiKeyPrefix["api_key"] != null) { + requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!! + } else { + requestConfig.headers["api_key"] = apiKey["api_key"]!! + } + } + } + if (requestConfig.headers[Authorization].isNullOrEmpty()) { + accessToken?.let { accessToken -> + requestConfig.headers[Authorization] = "Bearer " + accessToken + } + } + } + + protected inline fun request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse { + val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") + + // take authMethod from operation + updateAuthParams(requestConfig) + + val url = httpUrl.newBuilder() + .addPathSegments(requestConfig.path.trimStart('/')) + .apply { + requestConfig.query.forEach { query -> + query.value.forEach { queryValue -> + addQueryParameter(query.key, queryValue) + } + } + }.build() + + // take content-type/accept from spec or set to default (application/json) if not defined + if (requestConfig.headers[ContentType].isNullOrEmpty()) { + requestConfig.headers[ContentType] = JsonMediaType + } + if (requestConfig.headers[Accept].isNullOrEmpty()) { + requestConfig.headers[Accept] = JsonMediaType + } + val headers = requestConfig.headers + + if(headers[ContentType] ?: "" == "") { + throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") + } + + if(headers[Accept] ?: "" == "") { + throw kotlin.IllegalStateException("Missing Accept header. This is required.") + } + + // TODO: support multiple contentType options here. + val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + + val request = when (requestConfig.method) { + RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType)) + RequestMethod.GET -> Request.Builder().url(url) + RequestMethod.HEAD -> Request.Builder().url(url).head() + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType)) + RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) + }.apply { + headers.forEach { header -> addHeader(header.key, header.value) } + }.build() + + val response = client.newCall(request).execute() + val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + + // TODO: handle specific mapping types. e.g. Map> + when { + response.isRedirect -> return Redirection( + response.code, + response.headers.toMultimap() + ) + response.isInformational -> return Informational( + response.message, + response.code, + response.headers.toMultimap() + ) + response.isSuccessful -> return Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() + ) + response.isClientError -> return ClientError( + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + null, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected inline fun parseDateToQueryString(value : T): String { + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "") + } +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..f1a8aecc914 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,40 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +abstract class ApiInfrastructureResponse(val responseType: ResponseType) { + abstract val statusCode: Int + abstract val headers: Map> +} + +class Success( + val data: T, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiInfrastructureResponse(ResponseType.Success) + +class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Informational) + +class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Redirection) + +class ClientError( + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.ClientError) + +class ServerError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> +): ApiInfrastructureResponse(ResponseType.ServerError) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +object ApplicationDelegates { + /** + * Provides a property delegate, allowing the property to be set once and only once. + * + * If unset (no default value), a get on the property will throw [IllegalStateException]. + */ + fun setOnce(defaultValue: T? = null) : ReadWriteProperty = SetOnce(defaultValue) + + private class SetOnce(defaultValue: T? = null) : ReadWriteProperty { + private var isSet = false + private var value: T? = defaultValue + + override fun getValue(thisRef: Any?, property: KProperty<*>): T { + return value ?: throw IllegalStateException("${property.name} not initialized") + } + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) { + if (!isSet) { + this.value = value + isSet = true + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,12 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson + +class ByteArrayAdapter { + @ToJson + fun toJson(data: ByteArray): String = String(data) + + @FromJson + fun fromJson(data: String): ByteArray = data.toByteArray() +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..41f529a5f36 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package org.openapitools.client.infrastructure + +import java.lang.RuntimeException + +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter { + @ToJson + fun toJson(value: LocalDate): String { + return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDate { + return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + } + +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter { + @ToJson + fun toJson(value: LocalDateTime): String { + return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDateTime { + return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf() +) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..69b562becb0 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Response + +/** + * Provides an extension to evaluation whether the response is a 1xx code + */ +val Response.isInformational : Boolean get() = this.code in 100..199 + +/** + * Provides an extension to evaluation whether the response is a 3xx code + */ +val Response.isRedirect : Boolean get() = this.code in 300..399 + +/** + * Provides an extension to evaluation whether the response is a 4xx code + */ +val Response.isClientError : Boolean get() = this.code in 400..499 + +/** + * Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code + */ +val Response.isServerError : Boolean get() = this.code in 500..999 diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..3f39c48d4dc --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,22 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.Moshi +import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.util.Date + +object Serializer { + @JvmStatic + val moshiBuilder: Moshi.Builder = Moshi.Builder() + .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) + .add(LocalDateTimeAdapter()) + .add(LocalDateAdapter()) + .add(UUIDAdapter()) + .add(ByteArrayAdapter()) + .add(KotlinJsonAdapterFactory()) + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..47766821f18 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,33 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ + +data class ApiResponse ( + @Json(name = "code") + val code: kotlin.Int? = null, + @Json(name = "type") + val type: kotlin.String? = null, + @Json(name = "message") + val message: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..edb16cc1270 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,30 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A category for a pet + * @param id + * @param name + */ + +data class Category ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..bcdb149159b --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,55 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ + +data class Order ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "petId") + val petId: kotlin.Long? = null, + @Json(name = "quantity") + val quantity: kotlin.Int? = null, + @Json(name = "shipDate") + val shipDate: java.time.LocalDateTime? = null, + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + @Json(name = "complete") + val complete: kotlin.Boolean? = null +) + + +{ + /** + * Order Status + * Values: placed,approved,delivered + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "placed") placed("placed"), + @Json(name = "approved") approved("approved"), + @Json(name = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..ad4623a4ad1 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,57 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.squareup.moshi.Json +/** + * A pet for sale in the pet store + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ + +data class Pet ( + @Json(name = "name") + val name: kotlin.String, + @Json(name = "photoUrls") + val photoUrls: kotlin.Array, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.Array? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) + + +{ + /** + * pet status in the store + * Values: available,pending,sold + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..05dc7c9afef --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,30 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A tag for a pet + * @param id + * @param name + */ + +data class Tag ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..537b01d3c27 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-date/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,49 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ + +data class User ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "username") + val username: kotlin.String? = null, + @Json(name = "firstName") + val firstName: kotlin.String? = null, + @Json(name = "lastName") + val lastName: kotlin.String? = null, + @Json(name = "email") + val email: kotlin.String? = null, + @Json(name = "password") + val password: kotlin.String? = null, + @Json(name = "phone") + val phone: kotlin.String? = null, + /* User Status */ + @Json(name = "userStatus") + val userStatus: kotlin.Int? = null +) + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator-ignore b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/.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/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION new file mode 100644 index 00000000000..58592f031f6 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/README.md b/samples/client/petstore/kotlin-moshi-codegen/README.md new file mode 100644 index 00000000000..aef4ea15bee --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/README.md @@ -0,0 +1,90 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +## Requires + +* Kotlin 1.3.41 +* Gradle 4.9 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.ApiResponse](docs/ApiResponse.md) + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/kotlin-moshi-codegen/build.gradle b/samples/client/petstore/kotlin-moshi-codegen/build.gradle new file mode 100644 index 00000000000..aca00093000 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/build.gradle @@ -0,0 +1,39 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.61' + + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' +apply plugin: 'kotlin-kapt' + +repositories { + mavenCentral() +} + +test { + useJUnitPlatform() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + compile "com.squareup.moshi:moshi-adapters:1.9.2" + compile "com.squareup.moshi:moshi:1.9.2" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" + compile "com.squareup.okhttp3:okhttp:4.2.2" + testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/ApiResponse.md b/samples/client/petstore/kotlin-moshi-codegen/docs/ApiResponse.md new file mode 100644 index 00000000000..6b4c6bf2779 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/Category.md b/samples/client/petstore/kotlin-moshi-codegen/docs/Category.md new file mode 100644 index 00000000000..2c28a670fc7 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/Order.md b/samples/client/petstore/kotlin-moshi-codegen/docs/Order.md new file mode 100644 index 00000000000..ef31dbf2f4f --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**java.time.LocalDateTime**](java.time.LocalDateTime.md) | | [optional] +**status** | [**inline**](#StatusEnum) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/Pet.md b/samples/client/petstore/kotlin-moshi-codegen/docs/Pet.md new file mode 100644 index 00000000000..70c340005d1 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/PetApi.md b/samples/client/petstore/kotlin-moshi-codegen/docs/PetApi.md new file mode 100644 index 00000000000..ea93e174527 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/PetApi.md @@ -0,0 +1,405 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> kotlin.Array<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val status : kotlin.Array = // kotlin.Array | Status values that need to be considered for filter +try { + val result : kotlin.Array = apiInstance.findPetsByStatus(status) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.Array<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> kotlin.Array<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.Array = // kotlin.Array | Tags to filter by +try { + val result : kotlin.Array = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.Array<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload +try { + val result : ApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/StoreApi.md b/samples/client/petstore/kotlin-moshi-codegen/docs/StoreApi.md new file mode 100644 index 00000000000..f4986041af8 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/StoreApi.md @@ -0,0 +1,196 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val body : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(body) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/Tag.md b/samples/client/petstore/kotlin-moshi-codegen/docs/Tag.md new file mode 100644 index 00000000000..60ce1bcdbad --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/User.md b/samples/client/petstore/kotlin-moshi-codegen/docs/User.md new file mode 100644 index 00000000000..e801729b5ed --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/docs/UserApi.md b/samples/client/petstore/kotlin-moshi-codegen/docs/UserApi.md new file mode 100644 index 00000000000..0f55f06bc62 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : User = // User | Created user object +try { + apiInstance.createUser(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithArrayInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithListInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val body : User = // User | Updated user object +try { + apiInstance.updateUser(username, body) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-moshi-codegen/pom.xml b/samples/client/petstore/kotlin-moshi-codegen/pom.xml new file mode 100644 index 00000000000..9cae12c1a8b --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + io.swagger + KotlinMoshiPetstoreClientTests + pom + 1.0-SNAPSHOT + Kotlin Moshi Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-test + integration-test + + exec + + + gradle + + test + + + + + + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/settings.gradle b/samples/client/petstore/kotlin-moshi-codegen/settings.gradle new file mode 100644 index 00000000000..692eb84d7e1 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-moshi-codegen' \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..1638d460c68 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,366 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.ApiResponse +import org.openapitools.client.models.Pet + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun addPet(body: Pet) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("api_key" to apiKey.toString()) + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @return kotlin.Array + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun findPetsByStatus(status: kotlin.Array) : kotlin.Array { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("status", toMultiValue(status.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/findByStatus", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return kotlin.Array + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun findPetsByTags(tags: kotlin.Array) : kotlin.Array { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("tags", toMultiValue(tags.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/findByTags", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return Pet + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getPetById(petId: kotlin.Long) : Pet { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Pet + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePet(body: Pet) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { + val localVariableBody: kotlin.Any? = mapOf("name" to "$name", "status" to "$status") + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "") + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { + val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to "$additionalMetadata", "file" to "$file") + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "") + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..18355b552ae --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,192 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.Order + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteOrder(orderId: kotlin.String) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return kotlin.collections.Map + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getInventory() : kotlin.collections.Map { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/inventory", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request>( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getOrderById(orderId: kotlin.Long) : Order { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun placeOrder(body: Order) : Order { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/store/order", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..4f18a92d223 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,357 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.apis + +import org.openapitools.client.models.User + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiClient(basePath) { + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUser(body: User) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithArrayInput(body: kotlin.Array) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithArray", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithListInput(body: kotlin.Array) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithList", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteUser(username: kotlin.String) : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getUserByName(username: kotlin.String) : User { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return kotlin.String + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("username", listOf(username.toString())) + put("password", listOf(password.toString())) + } + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/login", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Logs out current logged in user session + * + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun logoutUser() : Unit { + val localVariableBody: kotlin.Any? = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/logout", + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updateUser(username: kotlin.String, body: User) : Unit { + val localVariableBody: kotlin.Any? = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/user/{username}".replace("{"+"username"+"}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders + ) + val localVarResponse = request( + localVariableConfig, + localVariableBody + ) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } + } + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 00000000000..ef7a8f1e1a6 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..de65b44cd9a --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,177 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Credentials +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.FormBody +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.ResponseBody +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.Request +import java.io.File + +open class ApiClient(val baseUrl: String) { + companion object { + protected const val ContentType = "Content-Type" + protected const val Accept = "Accept" + protected const val Authorization = "Authorization" + protected const val JsonMediaType = "application/json" + protected const val FormDataMediaType = "multipart/form-data" + protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded" + protected const val XmlMediaType = "application/xml" + + val apiKey: MutableMap = mutableMapOf() + val apiKeyPrefix: MutableMap = mutableMapOf() + var username: String? = null + var password: String? = null + var accessToken: String? = null + + @JvmStatic + val client: OkHttpClient by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() + } + + protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + when { + content is File -> content.asRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == FormDataMediaType || mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, value) + } + }.build() + } + mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody( + mediaType.toMediaTypeOrNull() + ) + mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") + // TODO: this should be extended with other serializers + else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") + } + + protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { + if(body == null) { + return null + } + val bodyContent = body.string() + if (bodyContent.isEmpty()) { + return null + } + return when(mediaType) { + JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) + else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") + } + } + + protected fun updateAuthParams(requestConfig: RequestConfig) { + if (requestConfig.headers["api_key"].isNullOrEmpty()) { + if (apiKey["api_key"] != null) { + if (apiKeyPrefix["api_key"] != null) { + requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!! + } else { + requestConfig.headers["api_key"] = apiKey["api_key"]!! + } + } + } + if (requestConfig.headers[Authorization].isNullOrEmpty()) { + accessToken?.let { accessToken -> + requestConfig.headers[Authorization] = "Bearer " + accessToken + } + } + } + + protected inline fun request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse { + val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") + + // take authMethod from operation + updateAuthParams(requestConfig) + + val url = httpUrl.newBuilder() + .addPathSegments(requestConfig.path.trimStart('/')) + .apply { + requestConfig.query.forEach { query -> + query.value.forEach { queryValue -> + addQueryParameter(query.key, queryValue) + } + } + }.build() + + // take content-type/accept from spec or set to default (application/json) if not defined + if (requestConfig.headers[ContentType].isNullOrEmpty()) { + requestConfig.headers[ContentType] = JsonMediaType + } + if (requestConfig.headers[Accept].isNullOrEmpty()) { + requestConfig.headers[Accept] = JsonMediaType + } + val headers = requestConfig.headers + + if(headers[ContentType] ?: "" == "") { + throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") + } + + if(headers[Accept] ?: "" == "") { + throw kotlin.IllegalStateException("Missing Accept header. This is required.") + } + + // TODO: support multiple contentType options here. + val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + + val request = when (requestConfig.method) { + RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType)) + RequestMethod.GET -> Request.Builder().url(url) + RequestMethod.HEAD -> Request.Builder().url(url).head() + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType)) + RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) + }.apply { + headers.forEach { header -> addHeader(header.key, header.value) } + }.build() + + val response = client.newCall(request).execute() + val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + + // TODO: handle specific mapping types. e.g. Map> + when { + response.isRedirect -> return Redirection( + response.code, + response.headers.toMultimap() + ) + response.isInformational -> return Informational( + response.message, + response.code, + response.headers.toMultimap() + ) + response.isSuccessful -> return Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() + ) + response.isClientError -> return ClientError( + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> return ServerError( + null, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt new file mode 100644 index 00000000000..f1a8aecc914 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt @@ -0,0 +1,40 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +abstract class ApiInfrastructureResponse(val responseType: ResponseType) { + abstract val statusCode: Int + abstract val headers: Map> +} + +class Success( + val data: T, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiInfrastructureResponse(ResponseType.Success) + +class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Informational) + +class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.Redirection) + +class ClientError( + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiInfrastructureResponse(ResponseType.ClientError) + +class ServerError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> +): ApiInfrastructureResponse(ResponseType.ServerError) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt new file mode 100644 index 00000000000..dd34bd48b2c --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +object ApplicationDelegates { + /** + * Provides a property delegate, allowing the property to be set once and only once. + * + * If unset (no default value), a get on the property will throw [IllegalStateException]. + */ + fun setOnce(defaultValue: T? = null) : ReadWriteProperty = SetOnce(defaultValue) + + private class SetOnce(defaultValue: T? = null) : ReadWriteProperty { + private var isSet = false + private var value: T? = defaultValue + + override fun getValue(thisRef: Any?, property: KProperty<*>): T { + return value ?: throw IllegalStateException("${property.name} not initialized") + } + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) { + if (!isSet) { + this.value = value + isSet = true + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,12 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson + +class ByteArrayAdapter { + @ToJson + fun toJson(data: ByteArray): String = String(data) + + @FromJson + fun fromJson(data: String): ByteArray = data.toByteArray() +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 00000000000..41f529a5f36 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package org.openapitools.client.infrastructure + +import java.lang.RuntimeException + +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter { + @ToJson + fun toJson(value: LocalDate): String { + return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDate { + return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter { + @ToJson + fun toJson(value: LocalDateTime): String { + return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDateTime { + return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 00000000000..9c22257e223 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf() +) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 00000000000..931b12b8bd7 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 00000000000..69b562becb0 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Response + +/** + * Provides an extension to evaluation whether the response is a 1xx code + */ +val Response.isInformational : Boolean get() = this.code in 100..199 + +/** + * Provides an extension to evaluation whether the response is a 3xx code + */ +val Response.isRedirect : Boolean get() = this.code in 300..399 + +/** + * Provides an extension to evaluation whether the response is a 4xx code + */ +val Response.isClientError : Boolean get() = this.code in 400..499 + +/** + * Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code + */ +val Response.isServerError : Boolean get() = this.code in 500..999 diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..2ea1cde78de --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,20 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.Moshi +import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter +import java.util.Date + +object Serializer { + @JvmStatic + val moshiBuilder: Moshi.Builder = Moshi.Builder() + .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) + .add(LocalDateTimeAdapter()) + .add(LocalDateAdapter()) + .add(UUIDAdapter()) + .add(ByteArrayAdapter()) + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..7db8d675141 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,34 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +@JsonClass(generateAdapter = true) +data class ApiResponse ( + @Json(name = "code") + val code: kotlin.Int? = null, + @Json(name = "type") + val type: kotlin.String? = null, + @Json(name = "message") + val message: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..e7a69536f8e --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,31 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * A category for a pet + * @param id + * @param name + */ +@JsonClass(generateAdapter = true) +data class Category ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..34441ed63c5 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,56 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +@JsonClass(generateAdapter = true) +data class Order ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "petId") + val petId: kotlin.Long? = null, + @Json(name = "quantity") + val quantity: kotlin.Int? = null, + @Json(name = "shipDate") + val shipDate: java.time.LocalDateTime? = null, + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + @Json(name = "complete") + val complete: kotlin.Boolean? = null +) + + +{ + /** + * Order Status + * Values: placed,approved,delivered + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "placed") placed("placed"), + @Json(name = "approved") approved("approved"), + @Json(name = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..d139610db01 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,58 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * A pet for sale in the pet store + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ +@JsonClass(generateAdapter = true) +data class Pet ( + @Json(name = "name") + val name: kotlin.String, + @Json(name = "photoUrls") + val photoUrls: kotlin.Array, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.Array? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) + + +{ + /** + * pet status in the store + * Values: available,pending,sold + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..3fd7bf14b7e --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,31 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * A tag for a pet + * @param id + * @param name + */ +@JsonClass(generateAdapter = true) +data class Tag ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..f91f96df6ac --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,50 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +@JsonClass(generateAdapter = true) +data class User ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "username") + val username: kotlin.String? = null, + @Json(name = "firstName") + val firstName: kotlin.String? = null, + @Json(name = "lastName") + val lastName: kotlin.String? = null, + @Json(name = "email") + val email: kotlin.String? = null, + @Json(name = "password") + val password: kotlin.String? = null, + @Json(name = "phone") + val phone: kotlin.String? = null, + /* User Status */ + @Json(name = "userStatus") + val userStatus: kotlin.Int? = null +) + + + diff --git a/samples/client/petstore/kotlin-multiplatform/docs/Pet.md b/samples/client/petstore/kotlin-multiplatform/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-multiplatform/docs/Pet.md +++ b/samples/client/petstore/kotlin-multiplatform/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt index 3ac5ce7bb12..583826a79a1 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt @@ -18,10 +18,10 @@ import kotlinx.serialization.* import kotlinx.serialization.internal.CommonEnumSerializer /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin-nonpublic/build.gradle b/samples/client/petstore/kotlin-nonpublic/build.gradle index d2b39bf5e9f..ed72aa19d9e 100644 --- a/samples/client/petstore/kotlin-nonpublic/build.gradle +++ b/samples/client/petstore/kotlin-nonpublic/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:4.2.2" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/samples/client/petstore/kotlin-nonpublic/docs/Pet.md b/samples/client/petstore/kotlin-nonpublic/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-nonpublic/docs/Pet.md +++ b/samples/client/petstore/kotlin-nonpublic/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index ed683e3a093..d4b862a21ae 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ internal class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 9c448c5bd18..f1b775deba8 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ internal class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2 ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ internal class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2 ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ internal class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2 ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ internal class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2 ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index da7eda47fea..0703be33057 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ internal class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2" ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index e9201e8a2a9..048c7f724a5 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ internal open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2521ff5e08f..0c5925723b2 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -internal open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +internal open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { internal companion object { private const val serialVersionUID: Long = 123L } } -internal open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +internal open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { internal companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 051082f5628..ae334fcad26 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date internal object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt index 2c0dcaa1a83..aedb57e436d 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -17,10 +17,10 @@ import org.openapitools.client.models.Tag import com.squareup.moshi.Json /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin-nullable/build.gradle b/samples/client/petstore/kotlin-nullable/build.gradle index d2b39bf5e9f..ed72aa19d9e 100644 --- a/samples/client/petstore/kotlin-nullable/build.gradle +++ b/samples/client/petstore/kotlin-nullable/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:4.2.2" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/samples/client/petstore/kotlin-nullable/docs/Pet.md b/samples/client/petstore/kotlin-nullable/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-nullable/docs/Pet.md +++ b/samples/client/petstore/kotlin-nullable/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-nullable/pom.xml b/samples/client/petstore/kotlin-nullable/pom.xml new file mode 100644 index 00000000000..2bf0f9666d6 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + io.swagger + KotlinNullablePetstoreClientTests + pom + 1.0-SNAPSHOT + Kotlin Nullable Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-test + integration-test + + exec + + + gradle + + test + + + + + + + + diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 6f9d73ae06e..3b1ecae4210 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 145423ba0b2..1a889435cd2 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 1f8df9953b1..3c561969920 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String? ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a83b73f51c..de65b44cd9a 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7c5a353e0f7..3f39c48d4dc 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt index 2f0e9aecfc1..eb78e6d7140 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,10 +18,10 @@ import com.squareup.moshi.Json import java.io.Serializable /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin-okhttp3/build.gradle b/samples/client/petstore/kotlin-okhttp3/build.gradle index 7272e8785fe..931aace4842 100644 --- a/samples/client/petstore/kotlin-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-okhttp3/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:3.12.6" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/samples/client/petstore/kotlin-okhttp3/docs/Pet.md b/samples/client/petstore/kotlin-okhttp3/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-okhttp3/docs/Pet.md +++ b/samples/client/petstore/kotlin-okhttp3/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 5eabd2dbcb4..1638d460c68 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 8f24aeabaaf..18355b552ae 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index db099377b83..4f18a92d223 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 162f8d23473..4cd44865752 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -168,4 +168,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7c5a353e0f7..3f39c48d4dc 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt index f6f7371601f..ad4623a4ad1 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -17,10 +17,10 @@ import org.openapitools.client.models.Tag import com.squareup.moshi.Json /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator-ignore b/samples/client/petstore/kotlin-retrofit2/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/.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/petstore/kotlin-retrofit2/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION new file mode 100644 index 00000000000..58592f031f6 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/README.md b/samples/client/petstore/kotlin-retrofit2/README.md new file mode 100644 index 00000000000..aef4ea15bee --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/README.md @@ -0,0 +1,90 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +## Requires + +* Kotlin 1.3.41 +* Gradle 4.9 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.ApiResponse](docs/ApiResponse.md) + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/kotlin-retrofit2/build.gradle b/samples/client/petstore/kotlin-retrofit2/build.gradle new file mode 100644 index 00000000000..ced65c34561 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/build.gradle @@ -0,0 +1,40 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.61' + ext.retrofitVersion = '2.6.2' + + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' + +repositories { + mavenCentral() +} + +test { + useJUnitPlatform() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" + compile "com.squareup.retrofit2:retrofit:$retrofitVersion" + compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" +} diff --git a/samples/client/petstore/kotlin-retrofit2/docs/ApiResponse.md b/samples/client/petstore/kotlin-retrofit2/docs/ApiResponse.md new file mode 100644 index 00000000000..6b4c6bf2779 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/Category.md b/samples/client/petstore/kotlin-retrofit2/docs/Category.md new file mode 100644 index 00000000000..2c28a670fc7 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/Order.md b/samples/client/petstore/kotlin-retrofit2/docs/Order.md new file mode 100644 index 00000000000..ef31dbf2f4f --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**java.time.LocalDateTime**](java.time.LocalDateTime.md) | | [optional] +**status** | [**inline**](#StatusEnum) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/Pet.md b/samples/client/petstore/kotlin-retrofit2/docs/Pet.md new file mode 100644 index 00000000000..70c340005d1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/PetApi.md b/samples/client/petstore/kotlin-retrofit2/docs/PetApi.md new file mode 100644 index 00000000000..ea93e174527 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/PetApi.md @@ -0,0 +1,405 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> kotlin.Array<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val status : kotlin.Array = // kotlin.Array | Status values that need to be considered for filter +try { + val result : kotlin.Array = apiInstance.findPetsByStatus(status) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.Array<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> kotlin.Array<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.Array = // kotlin.Array | Tags to filter by +try { + val result : kotlin.Array = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.Array<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.Array<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload +try { + val result : ApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/StoreApi.md b/samples/client/petstore/kotlin-retrofit2/docs/StoreApi.md new file mode 100644 index 00000000000..f4986041af8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/StoreApi.md @@ -0,0 +1,196 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val body : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(body) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/Tag.md b/samples/client/petstore/kotlin-retrofit2/docs/Tag.md new file mode 100644 index 00000000000..60ce1bcdbad --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/User.md b/samples/client/petstore/kotlin-retrofit2/docs/User.md new file mode 100644 index 00000000000..e801729b5ed --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2/docs/UserApi.md b/samples/client/petstore/kotlin-retrofit2/docs/UserApi.md new file mode 100644 index 00000000000..0f55f06bc62 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : User = // User | Created user object +try { + apiInstance.createUser(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithArrayInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.Array = // kotlin.Array | List of user object +try { + apiInstance.createUsersWithListInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.Array<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val body : User = // User | Updated user object +try { + apiInstance.updateUser(username, body) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-retrofit2/settings.gradle b/samples/client/petstore/kotlin-retrofit2/settings.gradle new file mode 100644 index 00000000000..24c556e079c --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-retrofit2' \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 00000000000..75f3323445c --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,41 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import okhttp3.ResponseBody +import okhttp3.MultipartBody + +import org.openapitools.client.models.ApiResponse +import org.openapitools.client.models.Pet + +interface PetApi { + @POST("/pet") + fun addPet(@Body body: Pet): Call + + @DELETE("/pet/{petId}") + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + + @GET("/pet/findByStatus") + fun findPetsByStatus(@Query("status") status: CSVParams): Call> + + @Deprecated("This api was deprecated") + @GET("/pet/findByTags") + fun findPetsByTags(@Query("tags") tags: CSVParams): Call> + + @GET("/pet/{petId}") + fun getPetById(@Path("petId") petId: kotlin.Long): Call + + @PUT("/pet") + fun updatePet(@Body body: Pet): Call + + @FormUrlEncoded + @POST("/pet/{petId}") + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Call + + @Multipart + @POST("/pet/{petId}/uploadImage") + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part ): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 00000000000..cb0d5b8fa1b --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,25 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import okhttp3.ResponseBody +import okhttp3.MultipartBody + +import org.openapitools.client.models.Order + +interface StoreApi { + @DELETE("/store/order/{orderId}") + fun deleteOrder(@Path("orderId") orderId: kotlin.String): Call + + @GET("/store/inventory") + fun getInventory(): Call> + + @GET("/store/order/{orderId}") + fun getOrderById(@Path("orderId") orderId: kotlin.Long): Call + + @POST("/store/order") + fun placeOrder(@Body body: Order): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 00000000000..84a6cd43e5e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,37 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import okhttp3.ResponseBody +import okhttp3.MultipartBody + +import org.openapitools.client.models.User + +interface UserApi { + @POST("/user") + fun createUser(@Body body: User): Call + + @POST("/user/createWithArray") + fun createUsersWithArrayInput(@Body body: kotlin.Array): Call + + @POST("/user/createWithList") + fun createUsersWithListInput(@Body body: kotlin.Array): Call + + @DELETE("/user/{username}") + fun deleteUser(@Path("username") username: kotlin.String): Call + + @GET("/user/{username}") + fun getUserByName(@Path("username") username: kotlin.String): Call + + @GET("/user/login") + fun loginUser(@Query("username") username: kotlin.String, @Query("password") password: kotlin.String): Call + + @GET("/user/logout") + fun logoutUser(): Call + + @PUT("/user/{username}") + fun updateUser(@Path("username") username: kotlin.String, @Body body: User): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 00000000000..b539fda7438 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,33 @@ +package org.openapitools.client.infrastructure + +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import retrofit2.converter.scalars.ScalarsConverterFactory +import retrofit2.converter.moshi.MoshiConverterFactory + +class ApiClient( + private var baseUrl: String = "http://petstore.swagger.io/v2", + private var okHttpClient: OkHttpClient +) { + init { + normalizeBaseUrl() + } + + val retrofitBuilder: Retrofit.Builder by lazy { + + Retrofit.Builder() + .baseUrl(baseUrl) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(MoshiConverterFactory.create(Serializer.moshi)) + } + + fun createService(serviceClass: Class): S { + return retrofitBuilder.client(okHttpClient).build().create(serviceClass) + } + + private fun normalizeBaseUrl() { + if (!baseUrl.endsWith("/")) { + baseUrl += "/" + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 00000000000..ff5e2a81ee8 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,12 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson + +class ByteArrayAdapter { + @ToJson + fun toJson(data: ByteArray): String = String(data) + + @FromJson + fun fromJson(data: String): ByteArray = data.toByteArray() +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt new file mode 100644 index 00000000000..001e99325d2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt @@ -0,0 +1,56 @@ +package org.openapitools.client.infrastructure + +class CollectionFormats { + + open class CSVParams { + + var params: List + + constructor(params: List) { + this.params = params + } + + constructor(vararg params: String) { + this.params = listOf(*params) + } + + override fun toString(): String { + return params.joinToString(",") + } + } + + open class SSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString(" ") + } + } + + class TSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("\t") + } + } + + class PIPESParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("|") + } + } + + class SPACEParams : SSVParams() +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 00000000000..b2e1654479a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter { + @ToJson + fun toJson(value: LocalDate): String { + return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDate { + return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 00000000000..e082db94811 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter { + @ToJson + fun toJson(value: LocalDateTime): String { + return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDateTime { + return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 00000000000..3f39c48d4dc --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,22 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.Moshi +import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.util.Date + +object Serializer { + @JvmStatic + val moshiBuilder: Moshi.Builder = Moshi.Builder() + .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) + .add(LocalDateTimeAdapter()) + .add(LocalDateAdapter()) + .add(UUIDAdapter()) + .add(ByteArrayAdapter()) + .add(KotlinJsonAdapterFactory()) + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 00000000000..a4a44cc18b7 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt new file mode 100644 index 00000000000..47766821f18 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -0,0 +1,33 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ + +data class ApiResponse ( + @Json(name = "code") + val code: kotlin.Int? = null, + @Json(name = "type") + val type: kotlin.String? = null, + @Json(name = "message") + val message: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 00000000000..edb16cc1270 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,30 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A category for a pet + * @param id + * @param name + */ + +data class Category ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 00000000000..bcdb149159b --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,55 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ + +data class Order ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "petId") + val petId: kotlin.Long? = null, + @Json(name = "quantity") + val quantity: kotlin.Int? = null, + @Json(name = "shipDate") + val shipDate: java.time.LocalDateTime? = null, + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + @Json(name = "complete") + val complete: kotlin.Boolean? = null +) + + +{ + /** + * Order Status + * Values: placed,approved,delivered + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "placed") placed("placed"), + @Json(name = "approved") approved("approved"), + @Json(name = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 00000000000..ad4623a4ad1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,57 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.squareup.moshi.Json +/** + * A pet for sale in the pet store + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ + +data class Pet ( + @Json(name = "name") + val name: kotlin.String, + @Json(name = "photoUrls") + val photoUrls: kotlin.Array, + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "category") + val category: Category? = null, + @Json(name = "tags") + val tags: kotlin.Array? = null, + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null +) + + +{ + /** + * pet status in the store + * Values: available,pending,sold + */ + + enum class Status(val value: kotlin.String){ + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 00000000000..05dc7c9afef --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,30 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A tag for a pet + * @param id + * @param name + */ + +data class Tag ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "name") + val name: kotlin.String? = null +) + + + diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 00000000000..537b01d3c27 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,49 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.client.models + + +import com.squareup.moshi.Json +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ + +data class User ( + @Json(name = "id") + val id: kotlin.Long? = null, + @Json(name = "username") + val username: kotlin.String? = null, + @Json(name = "firstName") + val firstName: kotlin.String? = null, + @Json(name = "lastName") + val lastName: kotlin.String? = null, + @Json(name = "email") + val email: kotlin.String? = null, + @Json(name = "password") + val password: kotlin.String? = null, + @Json(name = "phone") + val phone: kotlin.String? = null, + /* User Status */ + @Json(name = "userStatus") + val userStatus: kotlin.Int? = null +) + + + diff --git a/samples/client/petstore/kotlin-string/build.gradle b/samples/client/petstore/kotlin-string/build.gradle index d2b39bf5e9f..ed72aa19d9e 100644 --- a/samples/client/petstore/kotlin-string/build.gradle +++ b/samples/client/petstore/kotlin-string/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:4.2.2" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/samples/client/petstore/kotlin-string/docs/PetApi.md b/samples/client/petstore/kotlin-string/docs/PetApi.md index ea93e174527..d4cc830afe0 100644 --- a/samples/client/petstore/kotlin-string/docs/PetApi.md +++ b/samples/client/petstore/kotlin-string/docs/PetApi.md @@ -62,7 +62,7 @@ Configure petstore_auth: # **deletePet** -> deletePet(petId, apiKey) +> deletePet(apiKey, petId) Deletes a pet @@ -73,10 +73,10 @@ Deletes a pet //import org.openapitools.client.models.* val apiInstance = PetApi() -val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete val apiKey : kotlin.String = apiKey_example // kotlin.String | +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete try { - apiInstance.deletePet(petId, apiKey) + apiInstance.deletePet(apiKey, petId) } catch (e: ClientException) { println("4xx response calling PetApi#deletePet") e.printStackTrace() @@ -90,8 +90,8 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **kotlin.Long**| Pet id to delete | **apiKey** | **kotlin.String**| | [optional] + **petId** | **kotlin.Long**| Pet id to delete | ### Return type diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 5eabd2dbcb4..e475ddc88d8 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,23 +57,29 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } /** * Deletes a pet * - * @param petId Pet id to delete * @param apiKey (optional) + * @param petId Pet id to delete * @return void * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) - fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { + fun deletePet(apiKey: kotlin.String?, petId: kotlin.Long) : Unit { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("api_key" to apiKey.toString()) @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 8f24aeabaaf..18355b552ae 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index db099377b83..4f18a92d223 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a83b73f51c..de65b44cd9a 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7c5a353e0f7..3f39c48d4dc 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt index 2f0e9aecfc1..c6a47fdc0c4 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -27,14 +27,14 @@ import java.io.Serializable */ data class Pet ( - @Json(name = "name") - val name: kotlin.String, - @Json(name = "photoUrls") - val photoUrls: kotlin.Array, @Json(name = "id") val id: kotlin.Long? = null, @Json(name = "category") val category: Category? = null, + @Json(name = "name") + val name: kotlin.String, + @Json(name = "photoUrls") + val photoUrls: kotlin.Array, @Json(name = "tags") val tags: kotlin.Array? = null, /* pet status in the store */ diff --git a/samples/client/petstore/kotlin-string/src/test/kotlin/org/openapitools/client/PetApiTest.kt b/samples/client/petstore/kotlin-string/src/test/kotlin/org/openapitools/client/PetApiTest.kt index d1c20493bcc..e410c780b27 100644 --- a/samples/client/petstore/kotlin-string/src/test/kotlin/org/openapitools/client/PetApiTest.kt +++ b/samples/client/petstore/kotlin-string/src/test/kotlin/org/openapitools/client/PetApiTest.kt @@ -90,7 +90,7 @@ class PetApiTest : ShouldSpec() { } should("delete a pet") { - api.deletePet(petId, "apiKey") + api.deletePet("apiKey", petId) // verify updated Pet val exception = shouldThrow { diff --git a/samples/client/petstore/kotlin-threetenbp/build.gradle b/samples/client/petstore/kotlin-threetenbp/build.gradle index 613a199fea5..76686a86065 100644 --- a/samples/client/petstore/kotlin-threetenbp/build.gradle +++ b/samples/client/petstore/kotlin-threetenbp/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:4.2.2" compile "org.threeten:threetenbp:1.4.0" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" diff --git a/samples/client/petstore/kotlin-threetenbp/docs/Pet.md b/samples/client/petstore/kotlin-threetenbp/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin-threetenbp/docs/Pet.md +++ b/samples/client/petstore/kotlin-threetenbp/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 5eabd2dbcb4..1638d460c68 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 8f24aeabaaf..18355b552ae 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index db099377b83..4f18a92d223 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a83b73f51c..de65b44cd9a 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7c5a353e0f7..3f39c48d4dc 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt index f6f7371601f..ad4623a4ad1 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -17,10 +17,10 @@ import org.openapitools.client.models.Tag import com.squareup.moshi.Json /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/kotlin/build.gradle b/samples/client/petstore/kotlin/build.gradle index d2b39bf5e9f..ed72aa19d9e 100644 --- a/samples/client/petstore/kotlin/build.gradle +++ b/samples/client/petstore/kotlin/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.50' + ext.kotlin_version = '1.3.61' repositories { mavenCentral() @@ -30,8 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.8.0" - compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.moshi:moshi-kotlin:1.9.2" + compile "com.squareup.moshi:moshi-adapters:1.9.2" compile "com.squareup.okhttp3:okhttp:4.2.2" testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/samples/client/petstore/kotlin/docs/Pet.md b/samples/client/petstore/kotlin/docs/Pet.md index ec775600737..70c340005d1 100644 --- a/samples/client/petstore/kotlin/docs/Pet.md +++ b/samples/client/petstore/kotlin/docs/Pet.md @@ -4,10 +4,10 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**id** | **kotlin.Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] **name** | **kotlin.String** | | **photoUrls** | **kotlin.Array<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] **tags** | [**kotlin.Array<Tag>**](Tag.md) | | [optional] **status** | [**inline**](#StatusEnum) | pet status in the store | [optional] diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 5eabd2dbcb4..1638d460c68 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -57,8 +57,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -92,8 +98,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -130,8 +142,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -168,8 +186,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.Array ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -203,8 +227,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as Pet ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -237,8 +267,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -273,8 +309,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -310,8 +352,14 @@ class PetApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCli ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 8f24aeabaaf..18355b552ae 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -56,8 +56,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -125,8 +137,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -160,8 +178,14 @@ class StoreApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiC ResponseType.Success -> (localVarResponse as Success<*>).data as Order ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index db099377b83..4f18a92d223 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -56,8 +56,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -90,8 +96,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -124,8 +136,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -158,8 +176,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -193,8 +217,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as User ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -233,8 +263,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -266,8 +302,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } @@ -301,8 +343,14 @@ class UserApi(basePath: kotlin.String = "http://petstore.swagger.io/v2") : ApiCl ResponseType.Success -> Unit ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> throw ClientException((localVarResponse as ClientError<*>).body as? String ?: "Client error") - ResponseType.ServerError -> throw ServerException((localVarResponse as ServerError<*>).message ?: "Server error") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException(localVarError.body as? String ?: "Client error", localVarError.statusCode) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException(localVarError.message ?: "Server error", localVarError.statusCode) + } } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a83b73f51c..de65b44cd9a 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -170,4 +170,8 @@ open class ApiClient(val baseUrl: String) { ) } } + + protected inline fun parseDateToQueryString(value : T): String { + return value.toString() + } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt index 2f3b0157ba7..41f529a5f36 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -3,38 +3,14 @@ package org.openapitools.client.infrastructure import java.lang.RuntimeException -open class ClientException : RuntimeException { - - /** - * Constructs an [ClientException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ClientException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 123L } } -open class ServerException : RuntimeException { - - /** - * Constructs an [ServerException] with no detail message. - */ - constructor() : super() - - /** - * Constructs an [ServerException] with the specified detail message. - - * @param message the detail message. - */ - constructor(message: kotlin.String) : super(message) +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1) : RuntimeException(message) { companion object { private const val serialVersionUID: Long = 456L diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7c5a353e0f7..3f39c48d4dc 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -7,12 +7,16 @@ import java.util.Date object Serializer { @JvmStatic - val moshi: Moshi = Moshi.Builder() + val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) .add(KotlinJsonAdapterFactory()) - .build() + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt index 2f0e9aecfc1..eb78e6d7140 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,10 +18,10 @@ import com.squareup.moshi.Json import java.io.Serializable /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php index 6c30b5ef3f2..3f9e16f0115 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php @@ -82,8 +82,8 @@ class HeaderSelector { if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { return null; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; + } elseif ($jsonAccept = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept)) { + return implode(',', $jsonAccept); } else { return implode(',', $accept); } diff --git a/samples/client/petstore/python-asyncio/README.md b/samples/client/petstore/python-asyncio/README.md index 8534592c150..b92f4eecf8d 100644 --- a/samples/client/petstore/python-asyncio/README.md +++ b/samples/client/petstore/python-asyncio/README.md @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import petstore_api +import petstore_api ``` ### Setuptools diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index fa90c926dee..92d2ba108e3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -296,41 +296,37 @@ class Configuration(object): } ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/samples/client/petstore/python-experimental/README.md b/samples/client/petstore/python-experimental/README.md index 2a5a1f6c149..ffffbf80eb0 100644 --- a/samples/client/petstore/python-experimental/README.md +++ b/samples/client/petstore/python-experimental/README.md @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import petstore_api +import petstore_api ``` ### Setuptools @@ -48,7 +48,6 @@ Please follow the [installation procedure](#installation--usage) and then run th from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint @@ -56,13 +55,13 @@ from pprint import pprint configuration.host = "http://petstore.swagger.io:80/v2" # Create an instance of the API class api_instance = petstore_api.AnotherFakeApi(petstore_api.ApiClient(configuration)) -body = petstore_api.Client() # Client | client model +body = petstore_api.Client() # client.Client | client model try: # To test special tags api_response = api_instance.call_123_test_special_tags(body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` @@ -115,54 +114,67 @@ Class | Method | HTTP request | Description ## Documentation For Models - - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) - - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) - - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) - - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) - - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) - - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) - - [Animal](docs/Animal.md) - - [ApiResponse](docs/ApiResponse.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [CatAllOf](docs/CatAllOf.md) - - [Category](docs/Category.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [Dog](docs/Dog.md) - - [DogAllOf](docs/DogAllOf.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [File](docs/File.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [FormatTest](docs/FormatTest.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [List](docs/List.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [NumberOnly](docs/NumberOnly.md) - - [Order](docs/Order.md) - - [OuterComposite](docs/OuterComposite.md) - - [OuterEnum](docs/OuterEnum.md) - - [OuterNumber](docs/OuterNumber.md) - - [Pet](docs/Pet.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [StringBooleanMap](docs/StringBooleanMap.md) - - [Tag](docs/Tag.md) - - [TypeHolderDefault](docs/TypeHolderDefault.md) - - [TypeHolderExample](docs/TypeHolderExample.md) - - [User](docs/User.md) - - [XmlItem](docs/XmlItem.md) + - [additional_properties_any_type.AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [additional_properties_array.AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [additional_properties_boolean.AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) + - [additional_properties_class.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [additional_properties_integer.AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [additional_properties_number.AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [additional_properties_object.AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [additional_properties_string.AdditionalPropertiesString](docs/AdditionalPropertiesString.md) + - [animal.Animal](docs/Animal.md) + - [api_response.ApiResponse](docs/ApiResponse.md) + - [array_of_array_of_number_only.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [array_of_number_only.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [array_test.ArrayTest](docs/ArrayTest.md) + - [capitalization.Capitalization](docs/Capitalization.md) + - [cat.Cat](docs/Cat.md) + - [cat_all_of.CatAllOf](docs/CatAllOf.md) + - [category.Category](docs/Category.md) + - [child.Child](docs/Child.md) + - [child_all_of.ChildAllOf](docs/ChildAllOf.md) + - [child_cat.ChildCat](docs/ChildCat.md) + - [child_cat_all_of.ChildCatAllOf](docs/ChildCatAllOf.md) + - [child_dog.ChildDog](docs/ChildDog.md) + - [child_dog_all_of.ChildDogAllOf](docs/ChildDogAllOf.md) + - [child_lizard.ChildLizard](docs/ChildLizard.md) + - [child_lizard_all_of.ChildLizardAllOf](docs/ChildLizardAllOf.md) + - [class_model.ClassModel](docs/ClassModel.md) + - [client.Client](docs/Client.md) + - [dog.Dog](docs/Dog.md) + - [dog_all_of.DogAllOf](docs/DogAllOf.md) + - [enum_arrays.EnumArrays](docs/EnumArrays.md) + - [enum_class.EnumClass](docs/EnumClass.md) + - [enum_test.EnumTest](docs/EnumTest.md) + - [file.File](docs/File.md) + - [file_schema_test_class.FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [format_test.FormatTest](docs/FormatTest.md) + - [grandparent.Grandparent](docs/Grandparent.md) + - [grandparent_animal.GrandparentAnimal](docs/GrandparentAnimal.md) + - [has_only_read_only.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [list.List](docs/List.md) + - [map_test.MapTest](docs/MapTest.md) + - [mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [model200_response.Model200Response](docs/Model200Response.md) + - [model_return.ModelReturn](docs/ModelReturn.md) + - [name.Name](docs/Name.md) + - [number_only.NumberOnly](docs/NumberOnly.md) + - [order.Order](docs/Order.md) + - [outer_composite.OuterComposite](docs/OuterComposite.md) + - [outer_enum.OuterEnum](docs/OuterEnum.md) + - [outer_number.OuterNumber](docs/OuterNumber.md) + - [parent.Parent](docs/Parent.md) + - [parent_all_of.ParentAllOf](docs/ParentAllOf.md) + - [parent_pet.ParentPet](docs/ParentPet.md) + - [pet.Pet](docs/Pet.md) + - [read_only_first.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [special_model_name.SpecialModelName](docs/SpecialModelName.md) + - [string_boolean_map.StringBooleanMap](docs/StringBooleanMap.md) + - [tag.Tag](docs/Tag.md) + - [type_holder_default.TypeHolderDefault](docs/TypeHolderDefault.md) + - [type_holder_example.TypeHolderExample](docs/TypeHolderExample.md) + - [user.User](docs/User.md) + - [xml_item.XmlItem](docs/XmlItem.md) ## Documentation For Authorization diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesAnyType.md index 754b2f3ada4..d27928ab752 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesAnyType.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesAnyType.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesAnyType +# additional_properties_any_type.AdditionalPropertiesAnyType ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesArray.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesArray.md index 61ac566c14d..6eac3ace2ec 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesArray.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesArray.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesArray +# additional_properties_array.AdditionalPropertiesArray ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesBoolean.md index f2567f064cf..b403323c553 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesBoolean.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesBoolean.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesBoolean +# additional_properties_boolean.AdditionalPropertiesBoolean ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md index 1a379bff6f0..4b232aa174a 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesClass +# additional_properties_class.AdditionalPropertiesClass ## Properties Name | Type | Description | Notes @@ -11,9 +11,9 @@ Name | Type | Description | Notes **map_array_anytype** | **{str: ([bool, date, datetime, dict, float, int, list, str],)}** | | [optional] **map_map_string** | **{str: ({str: (str,)},)}** | | [optional] **map_map_anytype** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}** | | [optional] -**anytype_1** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional] -**anytype_2** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional] -**anytype_3** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional] +**anytype_1** | **bool, date, datetime, dict, float, int, list, str** | | [optional] +**anytype_2** | **bool, date, datetime, dict, float, int, list, str** | | [optional] +**anytype_3** | **bool, date, datetime, dict, float, int, list, str** | | [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/petstore/python-experimental/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesInteger.md index fe0ba709c8e..461419e0375 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesInteger.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesInteger.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesInteger +# additional_properties_integer.AdditionalPropertiesInteger ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesNumber.md index bec81854b95..e0e328aed8e 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesNumber.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesNumber.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesNumber +# additional_properties_number.AdditionalPropertiesNumber ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesObject.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesObject.md index 3fcf2c9299d..36026fe72f8 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesObject.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesObject.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesObject +# additional_properties_object.AdditionalPropertiesObject ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesString.md b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesString.md index bbe0b1cbbbb..41594fd730d 100644 --- a/samples/client/petstore/python-experimental/docs/AdditionalPropertiesString.md +++ b/samples/client/petstore/python-experimental/docs/AdditionalPropertiesString.md @@ -1,4 +1,4 @@ -# AdditionalPropertiesString +# additional_properties_string.AdditionalPropertiesString ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Animal.md b/samples/client/petstore/python-experimental/docs/Animal.md index e59166a62e8..fda84ee28ee 100644 --- a/samples/client/petstore/python-experimental/docs/Animal.md +++ b/samples/client/petstore/python-experimental/docs/Animal.md @@ -1,4 +1,4 @@ -# Animal +# animal.Animal ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/AnotherFakeApi.md b/samples/client/petstore/python-experimental/docs/AnotherFakeApi.md index 67906afc0cd..75406ffa107 100644 --- a/samples/client/petstore/python-experimental/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python-experimental/docs/AnotherFakeApi.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **call_123_test_special_tags** -> Client call_123_test_special_tags(body) +> client.Client call_123_test_special_tags(body) To test special tags @@ -20,18 +20,18 @@ To test special tags and operation ID starting with number from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.AnotherFakeApi() -body = petstore_api.Client() # Client | client model +body = petstore_api.Client() # client.Client | client model +# example passing only required values which don't have defaults set try: # To test special tags api_response = api_instance.call_123_test_special_tags(body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` @@ -39,11 +39,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **body** | [**client.Client**](Client.md)| client model | ### Return type -[**Client**](Client.md) +[**client.Client**](Client.md) ### Authorization diff --git a/samples/client/petstore/python-experimental/docs/ApiResponse.md b/samples/client/petstore/python-experimental/docs/ApiResponse.md index 8fc302305ab..8f7ffa46134 100644 --- a/samples/client/petstore/python-experimental/docs/ApiResponse.md +++ b/samples/client/petstore/python-experimental/docs/ApiResponse.md @@ -1,4 +1,4 @@ -# ApiResponse +# api_response.ApiResponse ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md index 1a68df0090b..ab82c8c556d 100644 --- a/samples/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md @@ -1,4 +1,4 @@ -# ArrayOfArrayOfNumberOnly +# array_of_array_of_number_only.ArrayOfArrayOfNumberOnly ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md b/samples/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md index b8a760f56dc..b8ffd843c8d 100644 --- a/samples/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md +++ b/samples/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md @@ -1,4 +1,4 @@ -# ArrayOfNumberOnly +# array_of_number_only.ArrayOfNumberOnly ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/ArrayTest.md b/samples/client/petstore/python-experimental/docs/ArrayTest.md index c677e324ad4..22f198440e7 100644 --- a/samples/client/petstore/python-experimental/docs/ArrayTest.md +++ b/samples/client/petstore/python-experimental/docs/ArrayTest.md @@ -1,11 +1,11 @@ -# ArrayTest +# array_test.ArrayTest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_of_string** | **[str]** | | [optional] **array_array_of_integer** | **[[int]]** | | [optional] -**array_array_of_model** | **[[ReadOnlyFirst]]** | | [optional] +**array_array_of_model** | [**[[read_only_first.ReadOnlyFirst]]**](ReadOnlyFirst.md) | | [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/petstore/python-experimental/docs/Capitalization.md b/samples/client/petstore/python-experimental/docs/Capitalization.md index 85d88d239ee..d402f2a571a 100644 --- a/samples/client/petstore/python-experimental/docs/Capitalization.md +++ b/samples/client/petstore/python-experimental/docs/Capitalization.md @@ -1,4 +1,4 @@ -# Capitalization +# capitalization.Capitalization ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Cat.md b/samples/client/petstore/python-experimental/docs/Cat.md index 8bdbf9b3bcc..1d7b5b26d71 100644 --- a/samples/client/petstore/python-experimental/docs/Cat.md +++ b/samples/client/petstore/python-experimental/docs/Cat.md @@ -1,4 +1,4 @@ -# Cat +# cat.Cat ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/CatAllOf.md b/samples/client/petstore/python-experimental/docs/CatAllOf.md index 35434374fc9..653bb0aa353 100644 --- a/samples/client/petstore/python-experimental/docs/CatAllOf.md +++ b/samples/client/petstore/python-experimental/docs/CatAllOf.md @@ -1,4 +1,4 @@ -# CatAllOf +# cat_all_of.CatAllOf ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Category.md b/samples/client/petstore/python-experimental/docs/Category.md index 33b2242d703..bb122d910fc 100644 --- a/samples/client/petstore/python-experimental/docs/Category.md +++ b/samples/client/petstore/python-experimental/docs/Category.md @@ -1,4 +1,4 @@ -# Category +# category.Category ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Child.md b/samples/client/petstore/python-experimental/docs/Child.md new file mode 100644 index 00000000000..bc3c7f3922d --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/Child.md @@ -0,0 +1,12 @@ +# child.Child + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [optional] +**tele_vision** | **bool** | | [optional] +**inter_net** | **bool** | | [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/petstore/python-experimental/docs/ChildAllOf.md b/samples/client/petstore/python-experimental/docs/ChildAllOf.md new file mode 100644 index 00000000000..9d2e42e1894 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildAllOf.md @@ -0,0 +1,10 @@ +# child_all_of.ChildAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**inter_net** | **bool** | | [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/petstore/python-experimental/docs/ChildCat.md b/samples/client/petstore/python-experimental/docs/ChildCat.md new file mode 100644 index 00000000000..8f5ea4b2ced --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildCat.md @@ -0,0 +1,11 @@ +# child_cat.ChildCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**name** | **str** | | [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/petstore/python-experimental/docs/ChildCatAllOf.md b/samples/client/petstore/python-experimental/docs/ChildCatAllOf.md new file mode 100644 index 00000000000..2e84f31081f --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildCatAllOf.md @@ -0,0 +1,10 @@ +# child_cat_all_of.ChildCatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [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/petstore/python-experimental/docs/ChildDog.md b/samples/client/petstore/python-experimental/docs/ChildDog.md new file mode 100644 index 00000000000..2680d987a45 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildDog.md @@ -0,0 +1,11 @@ +# child_dog.ChildDog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**bark** | **str** | | [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/petstore/python-experimental/docs/ChildDogAllOf.md b/samples/client/petstore/python-experimental/docs/ChildDogAllOf.md new file mode 100644 index 00000000000..c7dded9a6df --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildDogAllOf.md @@ -0,0 +1,10 @@ +# child_dog_all_of.ChildDogAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bark** | **str** | | [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/petstore/python-experimental/docs/ChildLizard.md b/samples/client/petstore/python-experimental/docs/ChildLizard.md new file mode 100644 index 00000000000..97b8891a27e --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildLizard.md @@ -0,0 +1,11 @@ +# child_lizard.ChildLizard + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**loves_rocks** | **bool** | | [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/petstore/python-experimental/docs/ChildLizardAllOf.md b/samples/client/petstore/python-experimental/docs/ChildLizardAllOf.md new file mode 100644 index 00000000000..517f1260b96 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ChildLizardAllOf.md @@ -0,0 +1,10 @@ +# child_lizard_all_of.ChildLizardAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**loves_rocks** | **bool** | | [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/petstore/python-experimental/docs/ClassModel.md b/samples/client/petstore/python-experimental/docs/ClassModel.md index 657d51a944d..3f5d0075c1b 100644 --- a/samples/client/petstore/python-experimental/docs/ClassModel.md +++ b/samples/client/petstore/python-experimental/docs/ClassModel.md @@ -1,4 +1,4 @@ -# ClassModel +# class_model.ClassModel Model for testing model with \"_class\" property ## Properties diff --git a/samples/client/petstore/python-experimental/docs/Client.md b/samples/client/petstore/python-experimental/docs/Client.md index 88e99384f92..4c7ce57f750 100644 --- a/samples/client/petstore/python-experimental/docs/Client.md +++ b/samples/client/petstore/python-experimental/docs/Client.md @@ -1,4 +1,4 @@ -# Client +# client.Client ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Dog.md b/samples/client/petstore/python-experimental/docs/Dog.md index 81de5678072..ec98b99dcec 100644 --- a/samples/client/petstore/python-experimental/docs/Dog.md +++ b/samples/client/petstore/python-experimental/docs/Dog.md @@ -1,4 +1,4 @@ -# Dog +# dog.Dog ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/DogAllOf.md b/samples/client/petstore/python-experimental/docs/DogAllOf.md index 36d3216f7b3..da3c29557df 100644 --- a/samples/client/petstore/python-experimental/docs/DogAllOf.md +++ b/samples/client/petstore/python-experimental/docs/DogAllOf.md @@ -1,4 +1,4 @@ -# DogAllOf +# dog_all_of.DogAllOf ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/EnumArrays.md b/samples/client/petstore/python-experimental/docs/EnumArrays.md index e0b5582e9d5..c2f22d45047 100644 --- a/samples/client/petstore/python-experimental/docs/EnumArrays.md +++ b/samples/client/petstore/python-experimental/docs/EnumArrays.md @@ -1,4 +1,4 @@ -# EnumArrays +# enum_arrays.EnumArrays ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/EnumClass.md b/samples/client/petstore/python-experimental/docs/EnumClass.md index 510dff4df0c..333307fde46 100644 --- a/samples/client/petstore/python-experimental/docs/EnumClass.md +++ b/samples/client/petstore/python-experimental/docs/EnumClass.md @@ -1,4 +1,4 @@ -# EnumClass +# enum_class.EnumClass ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/EnumTest.md b/samples/client/petstore/python-experimental/docs/EnumTest.md index 5fc28b6c1ce..94477ea5a51 100644 --- a/samples/client/petstore/python-experimental/docs/EnumTest.md +++ b/samples/client/petstore/python-experimental/docs/EnumTest.md @@ -1,4 +1,4 @@ -# EnumTest +# enum_test.EnumTest ## Properties Name | Type | Description | Notes @@ -7,7 +7,7 @@ Name | Type | Description | Notes **enum_string** | **str** | | [optional] **enum_integer** | **int** | | [optional] **enum_number** | **float** | | [optional] -**outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] +**outer_enum** | [**outer_enum.OuterEnum**](OuterEnum.md) | | [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/petstore/python-experimental/docs/FakeApi.md b/samples/client/petstore/python-experimental/docs/FakeApi.md index 0677687d592..610d804757b 100644 --- a/samples/client/petstore/python-experimental/docs/FakeApi.md +++ b/samples/client/petstore/python-experimental/docs/FakeApi.md @@ -34,17 +34,17 @@ this route creates an XmlItem from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -xml_item = petstore_api.XmlItem() # XmlItem | XmlItem Body +xml_item = petstore_api.XmlItem() # xml_item.XmlItem | XmlItem Body +# example passing only required values which don't have defaults set try: # creates an XmlItem api_instance.create_xml_item(xml_item) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->create_xml_item: %s\n" % e) ``` @@ -52,7 +52,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | + **xml_item** | [**xml_item.XmlItem**](XmlItem.md)| XmlItem Body | ### Return type @@ -87,17 +87,18 @@ Test serialization of outer boolean types from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() body = True # bool | Input boolean as post body (optional) +# example passing only required values which don't have defaults set +# and optional values try: api_response = api_instance.fake_outer_boolean_serialize(body=body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->fake_outer_boolean_serialize: %s\n" % e) ``` @@ -128,7 +129,7 @@ No authorization required [[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) # **fake_outer_composite_serialize** -> OuterComposite fake_outer_composite_serialize() +> outer_composite.OuterComposite fake_outer_composite_serialize() @@ -140,17 +141,18 @@ Test serialization of object with outer number type from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -body = petstore_api.OuterComposite() # OuterComposite | Input composite as post body (optional) +body = petstore_api.OuterComposite() # outer_composite.OuterComposite | Input composite as post body (optional) +# example passing only required values which don't have defaults set +# and optional values try: api_response = api_instance.fake_outer_composite_serialize(body=body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->fake_outer_composite_serialize: %s\n" % e) ``` @@ -158,11 +160,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + **body** | [**outer_composite.OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] ### Return type -[**OuterComposite**](OuterComposite.md) +[**outer_composite.OuterComposite**](OuterComposite.md) ### Authorization @@ -181,7 +183,7 @@ No authorization required [[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) # **fake_outer_enum_serialize** -> OuterEnum fake_outer_enum_serialize() +> outer_enum.OuterEnum fake_outer_enum_serialize() @@ -193,17 +195,18 @@ Test serialization of outer enum from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -body = OuterEnum("placed") # OuterEnum | Input enum as post body (optional) +body = petstore_api.OuterEnum("placed") # outer_enum.OuterEnum | Input enum as post body (optional) +# example passing only required values which don't have defaults set +# and optional values try: api_response = api_instance.fake_outer_enum_serialize(body=body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->fake_outer_enum_serialize: %s\n" % e) ``` @@ -211,11 +214,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterEnum**](str.md)| Input enum as post body | [optional] + **body** | [**outer_enum.OuterEnum**](OuterEnum.md)| Input enum as post body | [optional] ### Return type -[**OuterEnum**](OuterEnum.md) +[**outer_enum.OuterEnum**](OuterEnum.md) ### Authorization @@ -234,7 +237,7 @@ No authorization required [[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) # **fake_outer_number_serialize** -> OuterNumber fake_outer_number_serialize() +> outer_number.OuterNumber fake_outer_number_serialize() @@ -246,17 +249,18 @@ Test serialization of outer number types from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -body = OuterNumber(3.4) # OuterNumber | Input number as post body (optional) +body = petstore_api.OuterNumber(3.4) # outer_number.OuterNumber | Input number as post body (optional) +# example passing only required values which don't have defaults set +# and optional values try: api_response = api_instance.fake_outer_number_serialize(body=body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->fake_outer_number_serialize: %s\n" % e) ``` @@ -264,11 +268,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OuterNumber**](float.md)| Input number as post body | [optional] + **body** | [**outer_number.OuterNumber**](OuterNumber.md)| Input number as post body | [optional] ### Return type -[**OuterNumber**](OuterNumber.md) +[**outer_number.OuterNumber**](OuterNumber.md) ### Authorization @@ -299,17 +303,18 @@ Test serialization of outer string types from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() body = 'body_example' # str | Input string as post body (optional) +# example passing only required values which don't have defaults set +# and optional values try: api_response = api_instance.fake_outer_string_serialize(body=body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->fake_outer_string_serialize: %s\n" % e) ``` @@ -352,16 +357,16 @@ For this test, the body for this request much reference a schema named `File`. from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -body = petstore_api.FileSchemaTestClass() # FileSchemaTestClass | +body = petstore_api.FileSchemaTestClass() # file_schema_test_class.FileSchemaTestClass | +# example passing only required values which don't have defaults set try: api_instance.test_body_with_file_schema(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) ``` @@ -369,7 +374,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + **body** | [**file_schema_test_class.FileSchemaTestClass**](FileSchemaTestClass.md)| | ### Return type @@ -402,17 +407,17 @@ No authorization required from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() query = 'query_example' # str | -body = petstore_api.User() # User | +body = petstore_api.User() # user.User | +# example passing only required values which don't have defaults set try: api_instance.test_body_with_query_params(query, body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) ``` @@ -421,7 +426,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query** | **str**| | - **body** | [**User**](User.md)| | + **body** | [**user.User**](User.md)| | ### Return type @@ -444,7 +449,7 @@ No authorization required [[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) # **test_client_model** -> Client test_client_model(body) +> client.Client test_client_model(body) To test \"client\" model @@ -456,18 +461,18 @@ To test \"client\" model from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -body = petstore_api.Client() # Client | client model +body = petstore_api.Client() # client.Client | client model +# example passing only required values which don't have defaults set try: # To test \"client\" model api_response = api_instance.test_client_model(body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_client_model: %s\n" % e) ``` @@ -475,11 +480,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **body** | [**client.Client**](Client.md)| client model | ### Return type -[**Client**](Client.md) +[**client.Client**](Client.md) ### Authorization @@ -510,20 +515,15 @@ This route has required values with enums of 1 from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() -query_integer = 3 # int | (default to 3) -query_string = 'brillig' # str | (default to 'brillig') -path_string = 'hello' # str | (default to 'hello') -path_integer = 34 # int | (default to 34) -header_number = 1.234 # float | (default to 1.234) +# example passing only required values which don't have defaults set try: - api_instance.test_endpoint_enums_length_one(query_integer, query_string, path_string, path_integer, header_number) -except ApiException as e: + api_instance.test_endpoint_enums_length_one() +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) ``` @@ -571,7 +571,6 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure HTTP basic authorization: http_basic_test @@ -597,10 +596,19 @@ date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) param_callback = 'param_callback_example' # str | None (optional) +# example passing only required values which don't have defaults set +try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) +except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) ``` @@ -657,24 +665,25 @@ To test enum parameters from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() enum_header_string_array = ['enum_header_string_array_example'] # [str] | Header parameter enum test (string array) (optional) -enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to '-efg') +enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of '-efg' enum_query_string_array = ['enum_query_string_array_example'] # [str] | Query parameter enum test (string array) (optional) -enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to '-efg') +enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of '-efg' enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 3.4 # float | Query parameter enum test (double) (optional) -enum_form_string_array = '$' # [str] | Form parameter enum test (string array) (optional) (default to '$') -enum_form_string = '-efg' # str | Form parameter enum test (string) (optional) (default to '-efg') +enum_form_string_array = '$' # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of '$' +enum_form_string = '-efg' # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of '-efg' +# example passing only required values which don't have defaults set +# and optional values try: # To test enum parameters api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) ``` @@ -682,13 +691,13 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enum_header_string_array** | [**[str]**](str.md)| Header parameter enum test (string array) | [optional] + **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' - **enum_query_string_array** | [**[str]**](str.md)| Query parameter enum test (string array) | [optional] + **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_double** | **float**| Query parameter enum test (double) | [optional] - **enum_form_string_array** | [**[str]**](str.md)| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of '$' + **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of '$' **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' ### Return type @@ -725,7 +734,6 @@ Fake endpoint to test group parameters (optional) from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class @@ -737,10 +745,19 @@ string_group = 56 # int | String in group parameters (optional) boolean_group = True # bool | Boolean in group parameters (optional) int64_group = 56 # int | Integer in group parameters (optional) +# example passing only required values which don't have defaults set +try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) +except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # Fake endpoint to test group parameters (optional) api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) ``` @@ -786,17 +803,17 @@ test inline additionalProperties from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.FakeApi() param = {'key': 'param_example'} # {str: (str,)} | request body +# example passing only required values which don't have defaults set try: # test inline additionalProperties api_instance.test_inline_additional_properties(param) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) ``` @@ -804,7 +821,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **param** | [**{str: (str,)}**](str.md)| request body | + **param** | **{str: (str,)}**| request body | ### Return type @@ -837,7 +854,6 @@ test json serialization of form data from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class @@ -845,10 +861,11 @@ api_instance = petstore_api.FakeApi() param = 'param_example' # str | field1 param2 = 'param2_example' # str | field2 +# example passing only required values which don't have defaults set try: # test json serialization of form data api_instance.test_json_form_data(param, param2) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) ``` diff --git a/samples/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md index 321fd9e1854..2335c666fd8 100644 --- a/samples/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **test_classname** -> Client test_classname(body) +> client.Client test_classname(body) To test class name in snake case @@ -21,7 +21,6 @@ To test class name in snake case from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure API key authorization: api_key_query @@ -33,13 +32,14 @@ configuration.api_key['api_key_query'] = 'YOUR_API_KEY' configuration.host = "http://petstore.swagger.io:80/v2" # Create an instance of the API class api_instance = petstore_api.FakeClassnameTags123Api(petstore_api.ApiClient(configuration)) -body = petstore_api.Client() # Client | client model +body = petstore_api.Client() # client.Client | client model +# example passing only required values which don't have defaults set try: # To test class name in snake case api_response = api_instance.test_classname(body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling FakeClassnameTags123Api->test_classname: %s\n" % e) ``` @@ -47,11 +47,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | + **body** | [**client.Client**](Client.md)| client model | ### Return type -[**Client**](Client.md) +[**client.Client**](Client.md) ### Authorization diff --git a/samples/client/petstore/python-experimental/docs/File.md b/samples/client/petstore/python-experimental/docs/File.md index f17ba0057d0..2847323a098 100644 --- a/samples/client/petstore/python-experimental/docs/File.md +++ b/samples/client/petstore/python-experimental/docs/File.md @@ -1,4 +1,4 @@ -# File +# file.File Must be named `File` for test. ## Properties diff --git a/samples/client/petstore/python-experimental/docs/FileSchemaTestClass.md b/samples/client/petstore/python-experimental/docs/FileSchemaTestClass.md index d0a8bbaaba9..807350c62f2 100644 --- a/samples/client/petstore/python-experimental/docs/FileSchemaTestClass.md +++ b/samples/client/petstore/python-experimental/docs/FileSchemaTestClass.md @@ -1,10 +1,10 @@ -# FileSchemaTestClass +# file_schema_test_class.FileSchemaTestClass ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**file** | [**File**](File.md) | | [optional] -**files** | [**[File]**](File.md) | | [optional] +**file** | [**file.File**](File.md) | | [optional] +**files** | [**[file.File]**](File.md) | | [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/petstore/python-experimental/docs/FormatTest.md b/samples/client/petstore/python-experimental/docs/FormatTest.md index 083b0bd4c98..0f0e2f7cfe1 100644 --- a/samples/client/petstore/python-experimental/docs/FormatTest.md +++ b/samples/client/petstore/python-experimental/docs/FormatTest.md @@ -1,4 +1,4 @@ -# FormatTest +# format_test.FormatTest ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Grandparent.md b/samples/client/petstore/python-experimental/docs/Grandparent.md new file mode 100644 index 00000000000..66f49333838 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/Grandparent.md @@ -0,0 +1,10 @@ +# grandparent.Grandparent + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [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/petstore/python-experimental/docs/GrandparentAnimal.md b/samples/client/petstore/python-experimental/docs/GrandparentAnimal.md new file mode 100644 index 00000000000..8a6679f3895 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/GrandparentAnimal.md @@ -0,0 +1,10 @@ +# grandparent_animal.GrandparentAnimal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | + +[[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/petstore/python-experimental/docs/HasOnlyReadOnly.md b/samples/client/petstore/python-experimental/docs/HasOnlyReadOnly.md index f731a42eab5..f2194e269ed 100644 --- a/samples/client/petstore/python-experimental/docs/HasOnlyReadOnly.md +++ b/samples/client/petstore/python-experimental/docs/HasOnlyReadOnly.md @@ -1,4 +1,4 @@ -# HasOnlyReadOnly +# has_only_read_only.HasOnlyReadOnly ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/List.md b/samples/client/petstore/python-experimental/docs/List.md index 11f4f3a05f3..28e2ec05968 100644 --- a/samples/client/petstore/python-experimental/docs/List.md +++ b/samples/client/petstore/python-experimental/docs/List.md @@ -1,4 +1,4 @@ -# List +# list.List ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/MapTest.md b/samples/client/petstore/python-experimental/docs/MapTest.md index ad561b7220b..9fc13abebdc 100644 --- a/samples/client/petstore/python-experimental/docs/MapTest.md +++ b/samples/client/petstore/python-experimental/docs/MapTest.md @@ -1,4 +1,4 @@ -# MapTest +# map_test.MapTest ## Properties Name | Type | Description | Notes @@ -6,7 +6,7 @@ Name | Type | Description | Notes **map_map_of_string** | **{str: ({str: (str,)},)}** | | [optional] **map_of_enum_string** | **{str: (str,)}** | | [optional] **direct_map** | **{str: (bool,)}** | | [optional] -**indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] +**indirect_map** | [**string_boolean_map.StringBooleanMap**](StringBooleanMap.md) | | [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/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 1484c0638d8..87cda996e76 100644 --- a/samples/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -1,11 +1,11 @@ -# MixedPropertiesAndAdditionalPropertiesClass +# mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **str** | | [optional] **date_time** | **datetime** | | [optional] -**map** | [**{str: (Animal,)}**](Animal.md) | | [optional] +**map** | [**{str: (animal.Animal,)}**](Animal.md) | | [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/petstore/python-experimental/docs/Model200Response.md b/samples/client/petstore/python-experimental/docs/Model200Response.md index 40d0d7828e1..90f5c2c025d 100644 --- a/samples/client/petstore/python-experimental/docs/Model200Response.md +++ b/samples/client/petstore/python-experimental/docs/Model200Response.md @@ -1,4 +1,4 @@ -# Model200Response +# model200_response.Model200Response Model for testing model name starting with number ## Properties diff --git a/samples/client/petstore/python-experimental/docs/ModelReturn.md b/samples/client/petstore/python-experimental/docs/ModelReturn.md index 65ec73ddae7..3be9912b753 100644 --- a/samples/client/petstore/python-experimental/docs/ModelReturn.md +++ b/samples/client/petstore/python-experimental/docs/ModelReturn.md @@ -1,4 +1,4 @@ -# ModelReturn +# model_return.ModelReturn Model for testing reserved words ## Properties diff --git a/samples/client/petstore/python-experimental/docs/Name.md b/samples/client/petstore/python-experimental/docs/Name.md index 807b76afc6e..777b79a3d8b 100644 --- a/samples/client/petstore/python-experimental/docs/Name.md +++ b/samples/client/petstore/python-experimental/docs/Name.md @@ -1,4 +1,4 @@ -# Name +# name.Name Model for testing model name same as property name ## Properties diff --git a/samples/client/petstore/python-experimental/docs/NumberOnly.md b/samples/client/petstore/python-experimental/docs/NumberOnly.md index 93a0fde7b93..ea1a09d2934 100644 --- a/samples/client/petstore/python-experimental/docs/NumberOnly.md +++ b/samples/client/petstore/python-experimental/docs/NumberOnly.md @@ -1,4 +1,4 @@ -# NumberOnly +# number_only.NumberOnly ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Order.md b/samples/client/petstore/python-experimental/docs/Order.md index c21210a3bd5..9569ea55e55 100644 --- a/samples/client/petstore/python-experimental/docs/Order.md +++ b/samples/client/petstore/python-experimental/docs/Order.md @@ -1,4 +1,4 @@ -# Order +# order.Order ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/OuterComposite.md b/samples/client/petstore/python-experimental/docs/OuterComposite.md index 3df277a30fa..88a190c7df9 100644 --- a/samples/client/petstore/python-experimental/docs/OuterComposite.md +++ b/samples/client/petstore/python-experimental/docs/OuterComposite.md @@ -1,9 +1,9 @@ -# OuterComposite +# outer_composite.OuterComposite ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**my_number** | [**OuterNumber**](OuterNumber.md) | | [optional] +**my_number** | [**outer_number.OuterNumber**](OuterNumber.md) | | [optional] **my_string** | **str** | | [optional] **my_boolean** | **bool** | | [optional] diff --git a/samples/client/petstore/python-experimental/docs/OuterEnum.md b/samples/client/petstore/python-experimental/docs/OuterEnum.md index cba01706898..1428a27552d 100644 --- a/samples/client/petstore/python-experimental/docs/OuterEnum.md +++ b/samples/client/petstore/python-experimental/docs/OuterEnum.md @@ -1,4 +1,4 @@ -# OuterEnum +# outer_enum.OuterEnum ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/OuterNumber.md b/samples/client/petstore/python-experimental/docs/OuterNumber.md index 5d75342bd8e..7e3728b519c 100644 --- a/samples/client/petstore/python-experimental/docs/OuterNumber.md +++ b/samples/client/petstore/python-experimental/docs/OuterNumber.md @@ -1,4 +1,4 @@ -# OuterNumber +# outer_number.OuterNumber ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Parent.md b/samples/client/petstore/python-experimental/docs/Parent.md new file mode 100644 index 00000000000..2437d3c81ac --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/Parent.md @@ -0,0 +1,11 @@ +# parent.Parent + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [optional] +**tele_vision** | **bool** | | [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/petstore/python-experimental/docs/ParentAllOf.md b/samples/client/petstore/python-experimental/docs/ParentAllOf.md new file mode 100644 index 00000000000..6a27f70d4ad --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ParentAllOf.md @@ -0,0 +1,10 @@ +# parent_all_of.ParentAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tele_vision** | **bool** | | [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/petstore/python-experimental/docs/ParentPet.md b/samples/client/petstore/python-experimental/docs/ParentPet.md new file mode 100644 index 00000000000..12bfa5c7fe5 --- /dev/null +++ b/samples/client/petstore/python-experimental/docs/ParentPet.md @@ -0,0 +1,10 @@ +# parent_pet.ParentPet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | + +[[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/petstore/python-experimental/docs/Pet.md b/samples/client/petstore/python-experimental/docs/Pet.md index ce09d401c89..a1ea5598e86 100644 --- a/samples/client/petstore/python-experimental/docs/Pet.md +++ b/samples/client/petstore/python-experimental/docs/Pet.md @@ -1,4 +1,4 @@ -# Pet +# pet.Pet ## Properties Name | Type | Description | Notes @@ -6,8 +6,8 @@ Name | Type | Description | Notes **name** | **str** | | **photo_urls** | **[str]** | | **id** | **int** | | [optional] -**category** | [**Category**](Category.md) | | [optional] -**tags** | [**[Tag]**](Tag.md) | | [optional] +**category** | [**category.Category**](Category.md) | | [optional] +**tags** | [**[tag.Tag]**](Tag.md) | | [optional] **status** | **str** | pet status in the store | [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/petstore/python-experimental/docs/PetApi.md b/samples/client/petstore/python-experimental/docs/PetApi.md index 8364f8fa8fc..dbeb8dfe5ac 100644 --- a/samples/client/petstore/python-experimental/docs/PetApi.md +++ b/samples/client/petstore/python-experimental/docs/PetApi.md @@ -27,7 +27,6 @@ Add a new pet to the store from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -37,12 +36,13 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' configuration.host = "http://petstore.swagger.io:80/v2" # Create an instance of the API class api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) -body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store +body = petstore_api.Pet() # pet.Pet | Pet object that needs to be added to the store +# example passing only required values which don't have defaults set try: # Add a new pet to the store api_instance.add_pet(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->add_pet: %s\n" % e) ``` @@ -50,7 +50,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**pet.Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -85,7 +85,6 @@ Deletes a pet from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -98,10 +97,19 @@ api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 56 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) +# example passing only required values which don't have defaults set +try: + # Deletes a pet + api_instance.delete_pet(pet_id) +except petstore_api.ApiException as e: + print("Exception when calling PetApi->delete_pet: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->delete_pet: %s\n" % e) ``` @@ -134,7 +142,7 @@ void (empty response body) [[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) # **find_pets_by_status** -> [Pet] find_pets_by_status(status) +> [pet.Pet] find_pets_by_status(status) Finds Pets by status @@ -147,7 +155,6 @@ Multiple status values can be provided with comma separated strings from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -159,11 +166,12 @@ configuration.host = "http://petstore.swagger.io:80/v2" api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) status = ['status_example'] # [str] | Status values that need to be considered for filter +# example passing only required values which don't have defaults set try: # Finds Pets by status api_response = api_instance.find_pets_by_status(status) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) ``` @@ -171,11 +179,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**[str]**](str.md)| Status values that need to be considered for filter | + **status** | **[str]**| Status values that need to be considered for filter | ### Return type -[**[Pet]**](Pet.md) +[**[pet.Pet]**](Pet.md) ### Authorization @@ -195,7 +203,7 @@ Name | Type | Description | Notes [[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) # **find_pets_by_tags** -> [Pet] find_pets_by_tags(tags) +> [pet.Pet] find_pets_by_tags(tags) Finds Pets by tags @@ -208,7 +216,6 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -220,11 +227,12 @@ configuration.host = "http://petstore.swagger.io:80/v2" api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) tags = ['tags_example'] # [str] | Tags to filter by +# example passing only required values which don't have defaults set try: # Finds Pets by tags api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) ``` @@ -232,11 +240,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**[str]**](str.md)| Tags to filter by | + **tags** | **[str]**| Tags to filter by | ### Return type -[**[Pet]**](Pet.md) +[**[pet.Pet]**](Pet.md) ### Authorization @@ -256,7 +264,7 @@ Name | Type | Description | Notes [[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) # **get_pet_by_id** -> Pet get_pet_by_id(pet_id) +> pet.Pet get_pet_by_id(pet_id) Find pet by ID @@ -269,7 +277,6 @@ Returns a single pet from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure API key authorization: api_key @@ -283,11 +290,12 @@ configuration.host = "http://petstore.swagger.io:80/v2" api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) pet_id = 56 # int | ID of pet to return +# example passing only required values which don't have defaults set try: # Find pet by ID api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) ``` @@ -299,7 +307,7 @@ Name | Type | Description | Notes ### Return type -[**Pet**](Pet.md) +[**pet.Pet**](Pet.md) ### Authorization @@ -331,7 +339,6 @@ Update an existing pet from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -341,12 +348,13 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN' configuration.host = "http://petstore.swagger.io:80/v2" # Create an instance of the API class api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) -body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store +body = petstore_api.Pet() # pet.Pet | Pet object that needs to be added to the store +# example passing only required values which don't have defaults set try: # Update an existing pet api_instance.update_pet(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->update_pet: %s\n" % e) ``` @@ -354,7 +362,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**pet.Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -391,7 +399,6 @@ Updates a pet in the store with form data from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -405,10 +412,19 @@ pet_id = 56 # int | ID of pet that needs to be updated name = 'name_example' # str | Updated name of the pet (optional) status = 'status_example' # str | Updated status of the pet (optional) +# example passing only required values which don't have defaults set +try: + # Updates a pet in the store with form data + api_instance.update_pet_with_form(pet_id) +except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # Updates a pet in the store with form data api_instance.update_pet_with_form(pet_id, name=name, status=status) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) ``` @@ -441,7 +457,7 @@ void (empty response body) [[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) # **upload_file** -> ApiResponse upload_file(pet_id) +> api_response.ApiResponse upload_file(pet_id) uploads an image @@ -452,7 +468,6 @@ uploads an image from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -467,11 +482,21 @@ additional_metadata = 'additional_metadata_example' # str | Additional data to p file = open('/path/to/file', 'rb') # file_type | file to upload (optional) files = open('/path/to/file', 'rb') # [file_type] | files to upload (optional) +# example passing only required values which don't have defaults set +try: + # uploads an image + api_response = api_instance.upload_file(pet_id) + pprint(api_response) +except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # uploads an image api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file, files=files) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->upload_file: %s\n" % e) ``` @@ -482,11 +507,11 @@ Name | Type | Description | Notes **pet_id** | **int**| ID of pet to update | **additional_metadata** | **str**| Additional data to pass to server | [optional] **file** | **file_type**| file to upload | [optional] - **files** | [**[file_type]**](file_type.md)| files to upload | [optional] + **files** | **[file_type]**| files to upload | [optional] ### Return type -[**ApiResponse**](ApiResponse.md) +[**api_response.ApiResponse**](ApiResponse.md) ### Authorization @@ -505,7 +530,7 @@ Name | Type | Description | Notes [[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) # **upload_file_with_required_file** -> ApiResponse upload_file_with_required_file(pet_id, required_file) +> api_response.ApiResponse upload_file_with_required_file(pet_id, required_file) uploads an image (required) @@ -516,7 +541,6 @@ uploads an image (required) from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure OAuth2 access token for authorization: petstore_auth @@ -530,11 +554,21 @@ pet_id = 56 # int | ID of pet to update required_file = open('/path/to/file', 'rb') # file_type | file to upload additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) +# example passing only required values which don't have defaults set +try: + # uploads an image (required) + api_response = api_instance.upload_file_with_required_file(pet_id, required_file) + pprint(api_response) +except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) + +# example passing only required values which don't have defaults set +# and optional values try: # uploads an image (required) api_response = api_instance.upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) ``` @@ -548,7 +582,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**api_response.ApiResponse**](ApiResponse.md) ### Authorization diff --git a/samples/client/petstore/python-experimental/docs/ReadOnlyFirst.md b/samples/client/petstore/python-experimental/docs/ReadOnlyFirst.md index 6bc1447c1d7..252641787c3 100644 --- a/samples/client/petstore/python-experimental/docs/ReadOnlyFirst.md +++ b/samples/client/petstore/python-experimental/docs/ReadOnlyFirst.md @@ -1,4 +1,4 @@ -# ReadOnlyFirst +# read_only_first.ReadOnlyFirst ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/SpecialModelName.md b/samples/client/petstore/python-experimental/docs/SpecialModelName.md index 022ee19169c..312539af45e 100644 --- a/samples/client/petstore/python-experimental/docs/SpecialModelName.md +++ b/samples/client/petstore/python-experimental/docs/SpecialModelName.md @@ -1,4 +1,4 @@ -# SpecialModelName +# special_model_name.SpecialModelName ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/StoreApi.md b/samples/client/petstore/python-experimental/docs/StoreApi.md index bc010729c4e..6dfdac72b49 100644 --- a/samples/client/petstore/python-experimental/docs/StoreApi.md +++ b/samples/client/petstore/python-experimental/docs/StoreApi.md @@ -23,17 +23,17 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted +# example passing only required values which don't have defaults set try: # Delete purchase order by ID api_instance.delete_order(order_id) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling StoreApi->delete_order: %s\n" % e) ``` @@ -78,7 +78,6 @@ Returns a map of status codes to quantities from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint configuration = petstore_api.Configuration() # Configure API key authorization: api_key @@ -91,11 +90,12 @@ configuration.host = "http://petstore.swagger.io:80/v2" # Create an instance of the API class api_instance = petstore_api.StoreApi(petstore_api.ApiClient(configuration)) +# example, this endpoint has no required or optional parameters try: # Returns pet inventories by status api_response = api_instance.get_inventory() pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling StoreApi->get_inventory: %s\n" % e) ``` @@ -123,7 +123,7 @@ This endpoint does not need any parameter. [[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) # **get_order_by_id** -> Order get_order_by_id(order_id) +> order.Order get_order_by_id(order_id) Find purchase order by ID @@ -135,18 +135,18 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.StoreApi() order_id = 56 # int | ID of pet that needs to be fetched +# example passing only required values which don't have defaults set try: # Find purchase order by ID api_response = api_instance.get_order_by_id(order_id) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) ``` @@ -158,7 +158,7 @@ Name | Type | Description | Notes ### Return type -[**Order**](Order.md) +[**order.Order**](Order.md) ### Authorization @@ -179,7 +179,7 @@ No authorization required [[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) # **place_order** -> Order place_order(body) +> order.Order place_order(body) Place an order for a pet @@ -189,18 +189,18 @@ Place an order for a pet from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.StoreApi() -body = petstore_api.Order() # Order | order placed for purchasing the pet +body = petstore_api.Order() # order.Order | order placed for purchasing the pet +# example passing only required values which don't have defaults set try: # Place an order for a pet api_response = api_instance.place_order(body) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling StoreApi->place_order: %s\n" % e) ``` @@ -208,11 +208,11 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **body** | [**order.Order**](Order.md)| order placed for purchasing the pet | ### Return type -[**Order**](Order.md) +[**order.Order**](Order.md) ### Authorization diff --git a/samples/client/petstore/python-experimental/docs/StringBooleanMap.md b/samples/client/petstore/python-experimental/docs/StringBooleanMap.md index 2fbf3b3767d..2eb94fd9a73 100644 --- a/samples/client/petstore/python-experimental/docs/StringBooleanMap.md +++ b/samples/client/petstore/python-experimental/docs/StringBooleanMap.md @@ -1,4 +1,4 @@ -# StringBooleanMap +# string_boolean_map.StringBooleanMap ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/Tag.md b/samples/client/petstore/python-experimental/docs/Tag.md index 243cd98eda6..827e9db83e3 100644 --- a/samples/client/petstore/python-experimental/docs/Tag.md +++ b/samples/client/petstore/python-experimental/docs/Tag.md @@ -1,10 +1,11 @@ -# Tag +# tag.Tag ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] **name** | **str** | | [optional] +**full_name** | **str** | | [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/petstore/python-experimental/docs/TypeHolderDefault.md b/samples/client/petstore/python-experimental/docs/TypeHolderDefault.md index 21d125a8e5f..001509eba5f 100644 --- a/samples/client/petstore/python-experimental/docs/TypeHolderDefault.md +++ b/samples/client/petstore/python-experimental/docs/TypeHolderDefault.md @@ -1,4 +1,4 @@ -# TypeHolderDefault +# type_holder_default.TypeHolderDefault a model to test optional properties with server defaults ## Properties diff --git a/samples/client/petstore/python-experimental/docs/TypeHolderExample.md b/samples/client/petstore/python-experimental/docs/TypeHolderExample.md index b74c520d447..a681dc9440c 100644 --- a/samples/client/petstore/python-experimental/docs/TypeHolderExample.md +++ b/samples/client/petstore/python-experimental/docs/TypeHolderExample.md @@ -1,4 +1,4 @@ -# TypeHolderExample +# type_holder_example.TypeHolderExample a model to test required properties with an example and length one enum ## Properties diff --git a/samples/client/petstore/python-experimental/docs/User.md b/samples/client/petstore/python-experimental/docs/User.md index 443ac123fdc..52ff07af296 100644 --- a/samples/client/petstore/python-experimental/docs/User.md +++ b/samples/client/petstore/python-experimental/docs/User.md @@ -1,4 +1,4 @@ -# User +# user.User ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/docs/UserApi.md b/samples/client/petstore/python-experimental/docs/UserApi.md index d8d8b59a7d8..d93a4059c3b 100644 --- a/samples/client/petstore/python-experimental/docs/UserApi.md +++ b/samples/client/petstore/python-experimental/docs/UserApi.md @@ -27,17 +27,17 @@ This can only be done by the logged in user. from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() -body = petstore_api.User() # User | Created user object +body = petstore_api.User() # user.User | Created user object +# example passing only required values which don't have defaults set try: # Create user api_instance.create_user(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->create_user: %s\n" % e) ``` @@ -45,7 +45,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **body** | [**user.User**](User.md)| Created user object | ### Return type @@ -78,17 +78,17 @@ Creates list of users with given input array from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() -body = [petstore_api.User()] # [User] | List of user object +body = [petstore_api.User()] # [user.User] | List of user object +# example passing only required values which don't have defaults set try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) ``` @@ -96,7 +96,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | + **body** | [**[user.User]**](User.md)| List of user object | ### Return type @@ -129,17 +129,17 @@ Creates list of users with given input array from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() -body = [petstore_api.User()] # [User] | List of user object +body = [petstore_api.User()] # [user.User] | List of user object +# example passing only required values which don't have defaults set try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) ``` @@ -147,7 +147,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | + **body** | [**[user.User]**](User.md)| List of user object | ### Return type @@ -182,17 +182,17 @@ This can only be done by the logged in user. from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted +# example passing only required values which don't have defaults set try: # Delete user api_instance.delete_user(username) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->delete_user: %s\n" % e) ``` @@ -224,7 +224,7 @@ No authorization required [[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) # **get_user_by_name** -> User get_user_by_name(username) +> user.User get_user_by_name(username) Get user by user name @@ -234,18 +234,18 @@ Get user by user name from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. +# example passing only required values which don't have defaults set try: # Get user by user name api_response = api_instance.get_user_by_name(username) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->get_user_by_name: %s\n" % e) ``` @@ -257,7 +257,7 @@ Name | Type | Description | Notes ### Return type -[**User**](User.md) +[**user.User**](User.md) ### Authorization @@ -288,7 +288,6 @@ Logs user into the system from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class @@ -296,11 +295,12 @@ api_instance = petstore_api.UserApi() username = 'username_example' # str | The user name for login password = 'password_example' # str | The password for login in clear text +# example passing only required values which don't have defaults set try: # Logs user into the system api_response = api_instance.login_user(username, password) pprint(api_response) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->login_user: %s\n" % e) ``` @@ -343,16 +343,16 @@ Logs out current logged in user session from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() +# example, this endpoint has no required or optional parameters try: # Logs out current logged in user session api_instance.logout_user() -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->logout_user: %s\n" % e) ``` @@ -392,18 +392,18 @@ This can only be done by the logged in user. from __future__ import print_function import time import petstore_api -from petstore_api.rest import ApiException from pprint import pprint # Create an instance of the API class api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted -body = petstore_api.User() # User | Updated user object +body = petstore_api.User() # user.User | Updated user object +# example passing only required values which don't have defaults set try: # Updated user api_instance.update_user(username, body) -except ApiException as e: +except petstore_api.ApiException as e: print("Exception when calling UserApi->update_user: %s\n" % e) ``` @@ -412,7 +412,7 @@ except ApiException as e: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **body** | [**user.User**](User.md)| Updated user object | ### Return type diff --git a/samples/client/petstore/python-experimental/docs/XmlItem.md b/samples/client/petstore/python-experimental/docs/XmlItem.md index d30ca436229..0228e238165 100644 --- a/samples/client/petstore/python-experimental/docs/XmlItem.md +++ b/samples/client/petstore/python-experimental/docs/XmlItem.md @@ -1,4 +1,4 @@ -# XmlItem +# xml_item.XmlItem ## Properties Name | Type | Description | Notes diff --git a/samples/client/petstore/python-experimental/petstore_api/__init__.py b/samples/client/petstore/python-experimental/petstore_api/__init__.py index 905c4d34490..4b47774e2fd 100644 --- a/samples/client/petstore/python-experimental/petstore_api/__init__.py +++ b/samples/client/petstore/python-experimental/petstore_api/__init__.py @@ -26,12 +26,17 @@ from petstore_api.api.user_api import UserApi # import ApiClient from petstore_api.api_client import ApiClient + +# import Configuration from petstore_api.configuration import Configuration + +# import exceptions from petstore_api.exceptions import OpenApiException from petstore_api.exceptions import ApiTypeError from petstore_api.exceptions import ApiValueError from petstore_api.exceptions import ApiKeyError from petstore_api.exceptions import ApiException + # import models into sdk package from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType from petstore_api.models.additional_properties_array import AdditionalPropertiesArray @@ -50,6 +55,14 @@ from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.cat_all_of import CatAllOf from petstore_api.models.category import Category +from petstore_api.models.child import Child +from petstore_api.models.child_all_of import ChildAllOf +from petstore_api.models.child_cat import ChildCat +from petstore_api.models.child_cat_all_of import ChildCatAllOf +from petstore_api.models.child_dog import ChildDog +from petstore_api.models.child_dog_all_of import ChildDogAllOf +from petstore_api.models.child_lizard import ChildLizard +from petstore_api.models.child_lizard_all_of import ChildLizardAllOf from petstore_api.models.class_model import ClassModel from petstore_api.models.client import Client from petstore_api.models.dog import Dog @@ -60,6 +73,8 @@ from petstore_api.models.enum_test import EnumTest from petstore_api.models.file import File from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.format_test import FormatTest +from petstore_api.models.grandparent import Grandparent +from petstore_api.models.grandparent_animal import GrandparentAnimal from petstore_api.models.has_only_read_only import HasOnlyReadOnly from petstore_api.models.list import List from petstore_api.models.map_test import MapTest @@ -72,6 +87,9 @@ from petstore_api.models.order import Order from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_number import OuterNumber +from petstore_api.models.parent import Parent +from petstore_api.models.parent_all_of import ParentAllOf +from petstore_api.models.parent_pet import ParentPet from petstore_api.models.pet import Pet from petstore_api.models.read_only_first import ReadOnlyFirst from petstore_api.models.special_model_name import SpecialModelName @@ -81,4 +99,3 @@ from petstore_api.models.type_holder_default import TypeHolderDefault from petstore_api.models.type_holder_example import TypeHolderExample from petstore_api.models.user import User from petstore_api.models.xml_item import XmlItem - diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 2a875ae7876..c8e87491d52 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,7 +34,7 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.client import Client +from petstore_api.models import client class AnotherFakeApi(object): @@ -59,7 +60,7 @@ class AnotherFakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param Client body: client model (required) + :param client.Client body: client model (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -78,7 +79,7 @@ class AnotherFakeApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Client + :return: client.Client If the method is called asynchronously, returns the request thread. """ @@ -106,7 +107,7 @@ class AnotherFakeApi(object): self.call_123_test_special_tags = Endpoint( settings={ - 'response_type': (Client,), + 'response_type': (client.Client,), 'auth': [], 'endpoint_path': '/another-fake/dummy', 'operation_id': 'call_123_test_special_tags', @@ -133,7 +134,7 @@ class AnotherFakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Client,), + 'body': (client.Client,), }, 'attribute_map': { }, diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index c38dac0a5b0..31a6500d55f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,13 +34,13 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.client import Client -from petstore_api.models.file_schema_test_class import FileSchemaTestClass -from petstore_api.models.outer_composite import OuterComposite -from petstore_api.models.outer_enum import OuterEnum -from petstore_api.models.outer_number import OuterNumber -from petstore_api.models.user import User -from petstore_api.models.xml_item import XmlItem +from petstore_api.models import xml_item +from petstore_api.models import outer_composite +from petstore_api.models import outer_enum +from petstore_api.models import outer_number +from petstore_api.models import file_schema_test_class +from petstore_api.models import user +from petstore_api.models import client class FakeApi(object): @@ -65,7 +66,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param XmlItem xml_item: XmlItem Body (required) + :param xml_item.XmlItem xml_item: XmlItem Body (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -139,7 +140,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'xml_item': (XmlItem,), + 'xml_item': (xml_item.XmlItem,), }, 'attribute_map': { }, @@ -277,7 +278,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param OuterComposite body: Input composite as post body + :param outer_composite.OuterComposite body: Input composite as post body :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -296,7 +297,7 @@ class FakeApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: OuterComposite + :return: outer_composite.OuterComposite If the method is called asynchronously, returns the request thread. """ @@ -323,7 +324,7 @@ class FakeApi(object): self.fake_outer_composite_serialize = Endpoint( settings={ - 'response_type': (OuterComposite,), + 'response_type': (outer_composite.OuterComposite,), 'auth': [], 'endpoint_path': '/fake/outer/composite', 'operation_id': 'fake_outer_composite_serialize', @@ -348,7 +349,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (OuterComposite,), + 'body': (outer_composite.OuterComposite,), }, 'attribute_map': { }, @@ -379,7 +380,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param OuterEnum body: Input enum as post body + :param outer_enum.OuterEnum body: Input enum as post body :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -398,7 +399,7 @@ class FakeApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: OuterEnum + :return: outer_enum.OuterEnum If the method is called asynchronously, returns the request thread. """ @@ -425,7 +426,7 @@ class FakeApi(object): self.fake_outer_enum_serialize = Endpoint( settings={ - 'response_type': (OuterEnum,), + 'response_type': (outer_enum.OuterEnum,), 'auth': [], 'endpoint_path': '/fake/outer/enum', 'operation_id': 'fake_outer_enum_serialize', @@ -450,7 +451,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (OuterEnum,), + 'body': (outer_enum.OuterEnum,), }, 'attribute_map': { }, @@ -481,7 +482,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param OuterNumber body: Input number as post body + :param outer_number.OuterNumber body: Input number as post body :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -500,7 +501,7 @@ class FakeApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: OuterNumber + :return: outer_number.OuterNumber If the method is called asynchronously, returns the request thread. """ @@ -527,7 +528,7 @@ class FakeApi(object): self.fake_outer_number_serialize = Endpoint( settings={ - 'response_type': (OuterNumber,), + 'response_type': (outer_number.OuterNumber,), 'auth': [], 'endpoint_path': '/fake/outer/number', 'operation_id': 'fake_outer_number_serialize', @@ -552,7 +553,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (OuterNumber,), + 'body': (outer_number.OuterNumber,), }, 'attribute_map': { }, @@ -685,7 +686,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param FileSchemaTestClass body: (required) + :param file_schema_test_class.FileSchemaTestClass body: (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -759,7 +760,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (FileSchemaTestClass,), + 'body': (file_schema_test_class.FileSchemaTestClass,), }, 'attribute_map': { }, @@ -790,7 +791,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. :param str query: (required) - :param User body: (required) + :param user.User body: (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -868,7 +869,7 @@ class FakeApi(object): }, 'openapi_types': { 'query': (str,), - 'body': (User,), + 'body': (user.User,), }, 'attribute_map': { 'query': 'query', @@ -901,7 +902,7 @@ class FakeApi(object): :param async_req bool: execute request asynchronously Default is False. - :param Client body: client model (required) + :param client.Client body: client model (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -920,7 +921,7 @@ class FakeApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Client + :return: client.Client If the method is called asynchronously, returns the request thread. """ @@ -948,7 +949,7 @@ class FakeApi(object): self.test_client_model = Endpoint( settings={ - 'response_type': (Client,), + 'response_type': (client.Client,), 'auth': [], 'endpoint_path': '/fake', 'operation_id': 'test_client_model', @@ -975,7 +976,7 @@ class FakeApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Client,), + 'body': (client.Client,), }, 'attribute_map': { }, diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 45931801423..b10c7cd3915 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,7 +34,7 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.client import Client +from petstore_api.models import client class FakeClassnameTags123Api(object): @@ -59,7 +60,7 @@ class FakeClassnameTags123Api(object): :param async_req bool: execute request asynchronously Default is False. - :param Client body: client model (required) + :param client.Client body: client model (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -78,7 +79,7 @@ class FakeClassnameTags123Api(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Client + :return: client.Client If the method is called asynchronously, returns the request thread. """ @@ -106,7 +107,7 @@ class FakeClassnameTags123Api(object): self.test_classname = Endpoint( settings={ - 'response_type': (Client,), + 'response_type': (client.Client,), 'auth': [ 'api_key_query' ], @@ -135,7 +136,7 @@ class FakeClassnameTags123Api(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Client,), + 'body': (client.Client,), }, 'attribute_map': { }, diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index ba58ba92a81..e7e1cf19c00 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,8 +34,8 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.api_response import ApiResponse -from petstore_api.models.pet import Pet +from petstore_api.models import pet +from petstore_api.models import api_response class PetApi(object): @@ -59,7 +60,7 @@ class PetApi(object): :param async_req bool: execute request asynchronously Default is False. - :param Pet body: Pet object that needs to be added to the store (required) + :param pet.Pet body: Pet object that needs to be added to the store (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -135,7 +136,7 @@ class PetApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Pet,), + 'body': (pet.Pet,), }, 'attribute_map': { }, @@ -296,7 +297,7 @@ class PetApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: [Pet] + :return: [pet.Pet] If the method is called asynchronously, returns the request thread. """ @@ -324,7 +325,7 @@ class PetApi(object): self.find_pets_by_status = Endpoint( settings={ - 'response_type': ([Pet],), + 'response_type': ([pet.Pet],), 'auth': [ 'petstore_auth' ], @@ -413,7 +414,7 @@ class PetApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: [Pet] + :return: [pet.Pet] If the method is called asynchronously, returns the request thread. """ @@ -441,7 +442,7 @@ class PetApi(object): self.find_pets_by_tags = Endpoint( settings={ - 'response_type': ([Pet],), + 'response_type': ([pet.Pet],), 'auth': [ 'petstore_auth' ], @@ -523,7 +524,7 @@ class PetApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Pet + :return: pet.Pet If the method is called asynchronously, returns the request thread. """ @@ -551,7 +552,7 @@ class PetApi(object): self.get_pet_by_id = Endpoint( settings={ - 'response_type': (Pet,), + 'response_type': (pet.Pet,), 'auth': [ 'api_key' ], @@ -612,7 +613,7 @@ class PetApi(object): :param async_req bool: execute request asynchronously Default is False. - :param Pet body: Pet object that needs to be added to the store (required) + :param pet.Pet body: Pet object that needs to be added to the store (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -688,7 +689,7 @@ class PetApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Pet,), + 'body': (pet.Pet,), }, 'attribute_map': { }, @@ -858,7 +859,7 @@ class PetApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: ApiResponse + :return: api_response.ApiResponse If the method is called asynchronously, returns the request thread. """ @@ -886,7 +887,7 @@ class PetApi(object): self.upload_file = Endpoint( settings={ - 'response_type': (ApiResponse,), + 'response_type': (api_response.ApiResponse,), 'auth': [ 'petstore_auth' ], @@ -982,7 +983,7 @@ class PetApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: ApiResponse + :return: api_response.ApiResponse If the method is called asynchronously, returns the request thread. """ @@ -1011,7 +1012,7 @@ class PetApi(object): self.upload_file_with_required_file = Endpoint( settings={ - 'response_type': (ApiResponse,), + 'response_type': (api_response.ApiResponse,), 'auth': [ 'petstore_auth' ], diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index cdeebcce432..bb1367b167e 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,7 +34,7 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.order import Order +from petstore_api.models import order class StoreApi(object): @@ -282,7 +283,7 @@ class StoreApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Order + :return: order.Order If the method is called asynchronously, returns the request thread. """ @@ -310,7 +311,7 @@ class StoreApi(object): self.get_order_by_id = Endpoint( settings={ - 'response_type': (Order,), + 'response_type': (order.Order,), 'auth': [], 'endpoint_path': '/store/order/{order_id}', 'operation_id': 'get_order_by_id', @@ -375,7 +376,7 @@ class StoreApi(object): :param async_req bool: execute request asynchronously Default is False. - :param Order body: order placed for purchasing the pet (required) + :param order.Order body: order placed for purchasing the pet (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -394,7 +395,7 @@ class StoreApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: Order + :return: order.Order If the method is called asynchronously, returns the request thread. """ @@ -422,7 +423,7 @@ class StoreApi(object): self.place_order = Endpoint( settings={ - 'response_type': (Order,), + 'response_type': (order.Order,), 'auth': [], 'endpoint_path': '/store/order', 'operation_id': 'place_order', @@ -449,7 +450,7 @@ class StoreApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (Order,), + 'body': (order.Order,), }, 'attribute_map': { }, diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index 3e668cf374b..17e2428b84c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -13,6 +13,7 @@ from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 # python 2 and python 3 compatibility library import six @@ -33,7 +34,7 @@ from petstore_api.model_utils import ( # noqa: F401 str, validate_and_convert_types ) -from petstore_api.models.user import User +from petstore_api.models import user class UserApi(object): @@ -59,7 +60,7 @@ class UserApi(object): :param async_req bool: execute request asynchronously Default is False. - :param User body: Created user object (required) + :param user.User body: Created user object (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -133,7 +134,7 @@ class UserApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': (User,), + 'body': (user.User,), }, 'attribute_map': { }, @@ -161,7 +162,7 @@ class UserApi(object): :param async_req bool: execute request asynchronously Default is False. - :param [User] body: List of user object (required) + :param [user.User] body: List of user object (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -235,7 +236,7 @@ class UserApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': ([User],), + 'body': ([user.User],), }, 'attribute_map': { }, @@ -263,7 +264,7 @@ class UserApi(object): :param async_req bool: execute request asynchronously Default is False. - :param [User] body: List of user object (required) + :param [user.User] body: List of user object (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -337,7 +338,7 @@ class UserApi(object): 'allowed_values': { }, 'openapi_types': { - 'body': ([User],), + 'body': ([user.User],), }, 'attribute_map': { }, @@ -488,7 +489,7 @@ class UserApi(object): :param _host_index: integer specifying the index of the server that we want to use. Default is 0. - :return: User + :return: user.User If the method is called asynchronously, returns the request thread. """ @@ -516,7 +517,7 @@ class UserApi(object): self.get_user_by_name = Endpoint( settings={ - 'response_type': (User,), + 'response_type': (user.User,), 'auth': [], 'endpoint_path': '/user/{username}', 'operation_id': 'get_user_by_name', @@ -785,7 +786,7 @@ class UserApi(object): :param async_req bool: execute request asynchronously Default is False. :param str username: name that need to be deleted (required) - :param User body: Updated user object (required) + :param user.User body: Updated user object (required) :param _return_http_data_only: response data without head status code and headers. Default is True. :param _preload_content: if False, the urllib3.HTTPResponse object @@ -863,7 +864,7 @@ class UserApi(object): }, 'openapi_types': { 'username': (str,), - 'body': (User,), + 'body': (user.User,), }, 'attribute_map': { 'username': 'username', diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index 9a0c95c9045..f6f48362e57 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -300,41 +300,37 @@ class Configuration(object): } ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/samples/client/petstore/python-experimental/petstore_api/model_utils.py b/samples/client/petstore/python-experimental/petstore_api/model_utils.py index 22d9ee459de..5deb2458539 100644 --- a/samples/client/petstore/python-experimental/petstore_api/model_utils.py +++ b/samples/client/petstore/python-experimental/petstore_api/model_utils.py @@ -10,10 +10,10 @@ """ -import copy from datetime import date, datetime # noqa: F401 import inspect import os +import pprint import re import tempfile @@ -46,30 +46,297 @@ else: class OpenApiModel(object): """The base class for all OpenAPIModels""" + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._from_server, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value + ) + self.__dict__['_data_store'][name] = value + + def __setitem__(self, name, value): + """this allows us to set values with instance[field_name] = val""" + self.__setattr__(name, value) + + def __getitem__(self, name): + """this allows us to get a value with val = instance[field_name]""" + return self.__getattr__(name) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + if name in self.__dict__['_data_store']: + return self.__dict__['_data_store'][name] + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + [name] + ) + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + class ModelNormal(OpenApiModel): """the parent class of models whose type == object in their swagger/openapi""" + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + if name in self.__dict__['_data_store']: + return self.__dict__['_data_store'][name] + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + [name] + ) + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in six.iteritems(self._data_store): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if (not six.PY3 and + len(types) == 2 and unicode in types): # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf""" + + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + # set the attribute on the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + if model_instances: + for model_instance in model_instances: + if model_instance == self: + self.set_attribute(name, value) + else: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = ( + model_instance + ) + return None + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + if model_instances: + values = set() + for model_instance in model_instances: + if name in model_instance._data_store: + values.add(model_instance._data_store[name]) + if len(values) == 1: + return list(values)[0] + raise ApiValueError( + "Values stored for property {0} in {1} difffer when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + path_to_item + ) + + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in six.iteritems(self._data_store): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if (not six.PY3 and + len(types) == 2 and unicode in types): # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + COERCION_INDEX_BY_TYPE = { - ModelNormal: 0, - ModelSimple: 1, - none_type: 2, - list: 3, - dict: 4, - float: 5, - int: 6, - bool: 7, - datetime: 8, - date: 9, - str: 10, - file_type: 11, + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, } # these are used to limit what type conversions we try to do @@ -78,6 +345,8 @@ COERCION_INDEX_BY_TYPE = { UPCONVERSION_TYPE_PAIRS = ( (str, datetime), (str, date), + (list, ModelComposed), + (dict, ModelComposed), (list, ModelNormal), (dict, ModelNormal), (str, ModelSimple), @@ -88,6 +357,8 @@ UPCONVERSION_TYPE_PAIRS = ( COERCIBLE_TYPE_PAIRS = { False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), # (dict, ModelNormal), # (list, ModelNormal), # (str, ModelSimple), @@ -102,6 +373,8 @@ COERCIBLE_TYPE_PAIRS = { # (float, str), ), True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), (dict, ModelNormal), (list, ModelNormal), (str, ModelSimple), @@ -344,6 +617,9 @@ def order_response_types(required_types): return COERCION_INDEX_BY_TYPE[list] elif isinstance(class_or_instance, dict): return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] elif (inspect.isclass(class_or_instance) and issubclass(class_or_instance, ModelNormal)): return COERCION_INDEX_BY_TYPE[ModelNormal] @@ -385,7 +661,9 @@ def remove_uncoercible(required_types_classes, current_item, from_server, # convert our models to OpenApiModel required_type_class_simplified = required_type_class if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelNormal): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): required_type_class_simplified = ModelNormal elif issubclass(required_type_class_simplified, ModelSimple): required_type_class_simplified = ModelSimple @@ -522,6 +800,21 @@ def deserialize_primitive(data, klass, path_to_item): ) +def fix_model_input_data(model_data, model_class): + # this is only called on classes where the input data is a dict + fixed_model_data = change_keys_js_to_python( + model_data, + model_class + ) + if model_class._composed_schemas() is not None: + for allof_class in model_class._composed_schemas()['allOf']: + fixed_model_data = change_keys_js_to_python( + fixed_model_data, + allof_class + ) + return fixed_model_data + + def deserialize_model(model_data, model_class, path_to_item, check_type, configuration, from_server): """Deserializes model_data to model instance. @@ -544,42 +837,29 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, ApiValueError ApiKeyError """ - fixed_model_data = copy.deepcopy(model_data) - - if isinstance(fixed_model_data, dict): - fixed_model_data = change_keys_js_to_python(fixed_model_data, - model_class) kw_args = dict(_check_type=check_type, _path_to_item=path_to_item, _configuration=configuration, _from_server=from_server) - if hasattr(model_class, 'get_real_child_model'): - # discriminator case - discriminator_class = model_class.get_real_child_model(model_data) - if discriminator_class: - if isinstance(model_data, list): - instance = discriminator_class(*model_data, **kw_args) - elif isinstance(model_data, dict): - fixed_model_data = change_keys_js_to_python( - fixed_model_data, - discriminator_class - ) - kw_args.update(fixed_model_data) - instance = discriminator_class(**kw_args) - else: - # all other cases - if isinstance(model_data, list): - instance = model_class(*model_data, **kw_args) - if isinstance(model_data, dict): - fixed_model_data = change_keys_js_to_python(fixed_model_data, - model_class) - kw_args.update(fixed_model_data) - instance = model_class(**kw_args) - else: - instance = model_class(model_data, **kw_args) + used_model_class = model_class + if model_class.discriminator() is not None: + used_model_class = model_class.get_discriminator_class( + from_server, model_data) + if issubclass(used_model_class, ModelSimple): + instance = used_model_class(value=model_data, **kw_args) + return instance + if isinstance(model_data, list): + instance = used_model_class(*model_data, **kw_args) + if isinstance(model_data, dict): + fixed_model_data = change_keys_js_to_python( + model_data, + used_model_class + ) + kw_args.update(fixed_model_data) + instance = used_model_class(**kw_args) return instance @@ -634,7 +914,7 @@ def attempt_convert_item(input_value, valid_classes, path_to_item, key_type (bool): if True we need to convert a key type (not supported) must_convert (bool): if True we must convert check_type (bool): if True we check the type or the returned data in - ModelNormal and ModelSimple instances + ModelComposed/ModelNormal/ModelSimple instances Returns: instance (any) the fixed item @@ -798,27 +1078,31 @@ def model_to_dict(model_instance, serialize=True): """ result = {} - for attr, value in six.iteritems(model_instance._data_store): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: model_to_dict(x, serialize=serialize) - if hasattr(x, '_data_store') else x, value - )) - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], - model_to_dict(item[1], serialize=serialize)) - if hasattr(item[1], '_data_store') else item, - value.items() - )) - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value + model_instances = [model_instance] + if model_instance._composed_schemas() is not None: + model_instances = model_instance._composed_instances + for model_instance in model_instances: + for attr, value in six.iteritems(model_instance._data_store): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + attr = model_instance.attribute_map.get(attr, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: model_to_dict(x, serialize=serialize) + if hasattr(x, '_data_store') else x, value + )) + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], + model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], '_data_store') else item, + value.items() + )) + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value return result @@ -874,3 +1158,235 @@ def get_py3_class_name(input_class): elif input_class == int: return 'int' return input_class.__name__ + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas()['allOf']: + + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python( + model_args, allof_class) + + # extract a dict of only required keys from fixed_model_args + kwargs = {} + var_names = set(allof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + allof_instance = allof_class(**kwargs) + composed_instances.append(allof_instance) + return composed_instances + + +def get_oneof_instance(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + oneof_instance (instance) + """ + oneof_instance = None + if len(self._composed_schemas()['oneOf']) == 0: + return oneof_instance + + for oneof_class in self._composed_schemas()['oneOf']: + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python( + model_args, oneof_class) + + # extract a dict of only required keys from fixed_model_args + kwargs = {} + var_names = set(oneof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + try: + oneof_instance = oneof_class(**kwargs) + break + except Exception: + pass + if oneof_instance is None: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Unable to " + "make any instances of the classes in oneOf definition." % + self.__class__.__name__ + ) + return oneof_instance + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas()['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas()['anyOf']: + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python(model_args, anyof_class) + + # extract a dict of only required keys from these_model_vars + kwargs = {} + var_names = set(anyof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + try: + anyof_instance = anyof_class(**kwargs) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Unable to " + "make any instances of the classes in anyOf definition." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_additional_properties_model_instances( + composed_instances, self): + additional_properties_model_instances = [] + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + if instance.additional_properties_type is not None: + additional_properties_model_instances.append(instance) + return additional_properties_model_instances + + +def get_var_name_to_model_instances(self, composed_instances): + var_name_to_model_instances = {} + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + for var_name in instance.openapi_types: + if var_name not in var_name_to_model_instances: + var_name_to_model_instances[var_name] = [instance] + else: + var_name_to_model_instances[var_name].append(instance) + return var_name_to_model_instances + + +def get_unused_args(self, composed_instances, model_args): + unused_args = dict(model_args) + # arguments apssed to self were already converted to python names + # before __init__ was called + for var_name_py in self.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + for instance in composed_instances: + if instance.__class__ in self._composed_schemas()['allOf']: + for var_name_py in instance.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + else: + for var_name_js in instance.attribute_map.values(): + if var_name_js in unused_args: + del unused_args[var_name_js] + return unused_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas/classes, validates the classes to make sure that + they do not share any of the same parameters. If there is no collision + then composed model instances are created and returned tot the calling + self model + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas() + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + + # map variable names to composed_instances + var_name_to_model_instances = get_var_name_to_model_instances( + self, composed_instances) + + # set additional_properties_model_instances + additional_properties_model_instances = ( + get_additional_properties_model_instances(composed_instances, self) + ) + + # set any remaining values + unused_args = get_unused_args(self, composed_instances, model_args) + if len(unused_args) > 0: + if len(additional_properties_model_instances) == 0: + raise ApiValueError( + "Invalid input arguments input when making an instance of " + "class %s. Not all inputs were used. The unused input data " + "is %s" % (self.__class__.__name__, unused_args) + ) + for var_name, var_value in six.iteritems(unused_args): + for instance in additional_properties_model_instances: + setattr(instance, var_name, var_value) + # no need to add additional_properties to var_name_to_model_instances here + # because additional_properties_model_instances will direct us to that + # instance when we use getattr or setattr + # and we update var_name_to_model_instances in setattr + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances + ] diff --git a/samples/client/petstore/python-experimental/petstore_api/models/__init__.py b/samples/client/petstore/python-experimental/petstore_api/models/__init__.py index 1f2bb89aa33..e02c6651925 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/__init__.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/__init__.py @@ -11,54 +11,5 @@ """ -from __future__ import absolute_import - -# import models into model package -from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType -from petstore_api.models.additional_properties_array import AdditionalPropertiesArray -from petstore_api.models.additional_properties_boolean import AdditionalPropertiesBoolean -from petstore_api.models.additional_properties_class import AdditionalPropertiesClass -from petstore_api.models.additional_properties_integer import AdditionalPropertiesInteger -from petstore_api.models.additional_properties_number import AdditionalPropertiesNumber -from petstore_api.models.additional_properties_object import AdditionalPropertiesObject -from petstore_api.models.additional_properties_string import AdditionalPropertiesString -from petstore_api.models.animal import Animal -from petstore_api.models.api_response import ApiResponse -from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from petstore_api.models.array_of_number_only import ArrayOfNumberOnly -from petstore_api.models.array_test import ArrayTest -from petstore_api.models.capitalization import Capitalization -from petstore_api.models.cat import Cat -from petstore_api.models.cat_all_of import CatAllOf -from petstore_api.models.category import Category -from petstore_api.models.class_model import ClassModel -from petstore_api.models.client import Client -from petstore_api.models.dog import Dog -from petstore_api.models.dog_all_of import DogAllOf -from petstore_api.models.enum_arrays import EnumArrays -from petstore_api.models.enum_class import EnumClass -from petstore_api.models.enum_test import EnumTest -from petstore_api.models.file import File -from petstore_api.models.file_schema_test_class import FileSchemaTestClass -from petstore_api.models.format_test import FormatTest -from petstore_api.models.has_only_read_only import HasOnlyReadOnly -from petstore_api.models.list import List -from petstore_api.models.map_test import MapTest -from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass -from petstore_api.models.model200_response import Model200Response -from petstore_api.models.model_return import ModelReturn -from petstore_api.models.name import Name -from petstore_api.models.number_only import NumberOnly -from petstore_api.models.order import Order -from petstore_api.models.outer_composite import OuterComposite -from petstore_api.models.outer_enum import OuterEnum -from petstore_api.models.outer_number import OuterNumber -from petstore_api.models.pet import Pet -from petstore_api.models.read_only_first import ReadOnlyFirst -from petstore_api.models.special_model_name import SpecialModelName -from petstore_api.models.string_boolean_map import StringBooleanMap -from petstore_api.models.tag import Tag -from petstore_api.models.type_holder_default import TypeHolderDefault -from petstore_api.models.type_holder_example import TypeHolderExample -from petstore_api.models.user import User -from petstore_api.models.xml_item import XmlItem +# we can not import model classes here because that would create a circular +# reference which would not work in python2 diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py index 16b3e933e7f..e3bdd37fcc9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesAnyType(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesAnyType(ModelNormal): additional_properties_type = (bool, date, datetime, dict, float, int, list, str,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesAnyType - a model defined in OpenAPI + """additional_properties_any_type.AdditionalPropertiesAnyType - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesAnyType(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesAnyType(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesAnyType. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesAnyType. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesAnyType. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesAnyType): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py index 91e75256f55..12f228e9ba9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesArray(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesArray(ModelNormal): additional_properties_type = ([bool, date, datetime, dict, float, int, list, str],) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesArray - a model defined in OpenAPI + """additional_properties_array.AdditionalPropertiesArray - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesArray(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesArray(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesArray. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesArray. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesArray. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesArray): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py index ee30aacc80b..ed37ef90c4f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesBoolean(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesBoolean(ModelNormal): additional_properties_type = (bool,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesBoolean - a model defined in OpenAPI + """additional_properties_boolean.AdditionalPropertiesBoolean - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesBoolean(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesBoolean(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesBoolean. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesBoolean. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesBoolean. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesBoolean): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py index 407b63975b7..3f34d95684b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,20 +59,6 @@ class AdditionalPropertiesClass(ModelNormal): allowed_values = { } - attribute_map = { - 'map_string': 'map_string', # noqa: E501 - 'map_number': 'map_number', # noqa: E501 - 'map_integer': 'map_integer', # noqa: E501 - 'map_boolean': 'map_boolean', # noqa: E501 - 'map_array_integer': 'map_array_integer', # noqa: E501 - 'map_array_anytype': 'map_array_anytype', # noqa: E501 - 'map_map_string': 'map_map_string', # noqa: E501 - 'map_map_anytype': 'map_map_anytype', # noqa: E501 - 'anytype_1': 'anytype_1', # noqa: E501 - 'anytype_2': 'anytype_2', # noqa: E501 - 'anytype_3': 'anytype_3' # noqa: E501 - } - openapi_types = { 'map_string': ({str: (str,)},), # noqa: E501 'map_number': ({str: (float,)},), # noqa: E501 @@ -100,10 +78,38 @@ class AdditionalPropertiesClass(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'map_string': 'map_string', # noqa: E501 + 'map_number': 'map_number', # noqa: E501 + 'map_integer': 'map_integer', # noqa: E501 + 'map_boolean': 'map_boolean', # noqa: E501 + 'map_array_integer': 'map_array_integer', # noqa: E501 + 'map_array_anytype': 'map_array_anytype', # noqa: E501 + 'map_map_string': 'map_map_string', # noqa: E501 + 'map_map_anytype': 'map_map_anytype', # noqa: E501 + 'anytype_1': 'anytype_1', # noqa: E501 + 'anytype_2': 'anytype_2', # noqa: E501 + 'anytype_3': 'anytype_3', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesClass - a model defined in OpenAPI + """additional_properties_class.AdditionalPropertiesClass - a model defined in OpenAPI Keyword Args: @@ -132,6 +138,7 @@ class AdditionalPropertiesClass(ModelNormal): anytype_2 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501 anytype_3 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -139,276 +146,4 @@ class AdditionalPropertiesClass(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def map_string(self): - """Gets the map_string of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: (str,)}): The map_string of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_string') - - @map_string.setter - def map_string(self, value): - """Sets the map_string of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_string', value) - - @property - def map_number(self): - """Gets the map_number of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: (float,)}): The map_number of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_number') - - @map_number.setter - def map_number(self, value): - """Sets the map_number of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_number', value) - - @property - def map_integer(self): - """Gets the map_integer of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: (int,)}): The map_integer of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_integer') - - @map_integer.setter - def map_integer(self, value): - """Sets the map_integer of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_integer', value) - - @property - def map_boolean(self): - """Gets the map_boolean of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: (bool,)}): The map_boolean of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_boolean') - - @map_boolean.setter - def map_boolean(self, value): - """Sets the map_boolean of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_boolean', value) - - @property - def map_array_integer(self): - """Gets the map_array_integer of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: ([int],)}): The map_array_integer of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_array_integer') - - @map_array_integer.setter - def map_array_integer(self, value): - """Sets the map_array_integer of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_array_integer', value) - - @property - def map_array_anytype(self): - """Gets the map_array_anytype of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: ([bool, date, datetime, dict, float, int, list, str],)}): The map_array_anytype of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_array_anytype') - - @map_array_anytype.setter - def map_array_anytype(self, value): - """Sets the map_array_anytype of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_array_anytype', value) - - @property - def map_map_string(self): - """Gets the map_map_string of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: ({str: (str,)},)}): The map_map_string of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_map_string') - - @map_map_string.setter - def map_map_string(self, value): - """Sets the map_map_string of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_map_string', value) - - @property - def map_map_anytype(self): - """Gets the map_map_anytype of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}): The map_map_anytype of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map_map_anytype') - - @map_map_anytype.setter - def map_map_anytype(self, value): - """Sets the map_map_anytype of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map_map_anytype', value) - - @property - def anytype_1(self): - """Gets the anytype_1 of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - (bool, date, datetime, dict, float, int, list, str): The anytype_1 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('anytype_1') - - @anytype_1.setter - def anytype_1(self, value): - """Sets the anytype_1 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('anytype_1', value) - - @property - def anytype_2(self): - """Gets the anytype_2 of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - (bool, date, datetime, dict, float, int, list, str): The anytype_2 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('anytype_2') - - @anytype_2.setter - def anytype_2(self, value): - """Sets the anytype_2 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('anytype_2', value) - - @property - def anytype_3(self): - """Gets the anytype_3 of this AdditionalPropertiesClass. # noqa: E501 - - Returns: - (bool, date, datetime, dict, float, int, list, str): The anytype_3 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('anytype_3') - - @anytype_3.setter - def anytype_3(self, value): - """Sets the anytype_3 of this AdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('anytype_3', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesClass): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py index 558f48422a4..653350f6b55 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesInteger(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesInteger(ModelNormal): additional_properties_type = (int,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesInteger - a model defined in OpenAPI + """additional_properties_integer.AdditionalPropertiesInteger - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesInteger(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesInteger(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesInteger. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesInteger. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesInteger. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesInteger): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py index 25c9298cea9..e6d75b40636 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesNumber(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesNumber(ModelNormal): additional_properties_type = (float,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesNumber - a model defined in OpenAPI + """additional_properties_number.AdditionalPropertiesNumber - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesNumber(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesNumber(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesNumber. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesNumber. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesNumber. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesNumber): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py index 67acc4099b8..a3cb690eb76 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesObject(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesObject(ModelNormal): additional_properties_type = ({str: (bool, date, datetime, dict, float, int, list, str,)},) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesObject - a model defined in OpenAPI + """additional_properties_object.AdditionalPropertiesObject - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesObject(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesObject(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesObject. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesObject. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesObject. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesObject): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py index 5906157a158..1611d7c6408 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class AdditionalPropertiesString(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name' # noqa: E501 - } - openapi_types = { 'name': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class AdditionalPropertiesString(ModelNormal): additional_properties_type = (str,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """AdditionalPropertiesString - a model defined in OpenAPI + """additional_properties_string.AdditionalPropertiesString - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class AdditionalPropertiesString(ModelNormal): If omitted no type conversion is done. name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class AdditionalPropertiesString(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this AdditionalPropertiesString. # noqa: E501 - - Returns: - (str): The name of this AdditionalPropertiesString. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this AdditionalPropertiesString. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AdditionalPropertiesString): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/animal.py b/samples/client/petstore/python-experimental/petstore_api/models/animal.py index d625389dd63..106bf5e7649 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/animal.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/animal.py @@ -10,34 +10,32 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.cat import Cat -from petstore_api.models.dog import Dog +try: + from petstore_api.models import cat +except ImportError: + cat = sys.modules['petstore_api.models.cat'] +try: + from petstore_api.models import dog +except ImportError: + dog = sys.modules['petstore_api.models.dog'] class Animal(ModelNormal): @@ -69,16 +67,6 @@ class Animal(ModelNormal): allowed_values = { } - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'color': 'color' # noqa: E501 - } - - discriminator_value_class_map = { - 'Dog': Dog, - 'Cat': Cat - } - openapi_types = { 'class_name': (str,), # noqa: E501 'color': (str,), # noqa: E501 @@ -89,10 +77,34 @@ class Animal(ModelNormal): additional_properties_type = None - discriminator = 'class_name' + @staticmethod + def discriminator(): + return { + 'class_name': { + 'Cat': cat.Cat, + 'Dog': dog.Dog, + }, + } + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Animal - a model defined in OpenAPI + """animal.Animal - a model defined in OpenAPI Args: class_name (str): @@ -113,158 +125,26 @@ class Animal(ModelNormal): If omitted no type conversion is done. color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('class_name', class_name) + self.class_name = class_name for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def class_name(self): - """Gets the class_name of this Animal. # noqa: E501 - - Returns: - (str): The class_name of this Animal. # noqa: E501 - """ - return self.__get_item('class_name') - - @class_name.setter - def class_name(self, value): - """Sets the class_name of this Animal. # noqa: E501 - """ - return self.__set_item('class_name', value) - - @property - def color(self): - """Gets the color of this Animal. # noqa: E501 - - Returns: - (str): The color of this Animal. # noqa: E501 - """ - return self.__get_item('color') - - @color.setter - def color(self, value): - """Sets the color of this Animal. # noqa: E501 - """ - return self.__set_item('color', value) + setattr(self, var_name, var_value) @classmethod - def get_real_child_model(cls, data): - """Returns the real base class specified by the discriminator - We assume that data has javascript keys - """ - discriminator_key = cls.attribute_map[cls.discriminator] - discriminator_value = data[discriminator_key] - return cls.discriminator_value_class_map.get(discriminator_value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Animal): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + def get_discriminator_class(cls, from_server, data): + """Returns the child class specified by the discriminator""" + discriminator = cls.discriminator() + discr_propertyname_py = list(discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if from_server: + class_name = data[discr_propertyname_js] + else: + class_name = data[discr_propertyname_py] + class_name_to_discr_class = discriminator[discr_propertyname_py] + return class_name_to_discr_class.get(class_name) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/api_response.py b/samples/client/petstore/python-experimental/petstore_api/models/api_response.py index 40713b75479..e7516d6c759 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/api_response.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,12 +59,6 @@ class ApiResponse(ModelNormal): allowed_values = { } - attribute_map = { - 'code': 'code', # noqa: E501 - 'type': 'type', # noqa: E501 - 'message': 'message' # noqa: E501 - } - openapi_types = { 'code': (int,), # noqa: E501 'type': (str,), # noqa: E501 @@ -84,10 +70,30 @@ class ApiResponse(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'code': 'code', # noqa: E501 + 'type': 'type', # noqa: E501 + 'message': 'message', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ApiResponse - a model defined in OpenAPI + """api_response.ApiResponse - a model defined in OpenAPI Keyword Args: @@ -108,6 +114,7 @@ class ApiResponse(ModelNormal): type (str): [optional] # noqa: E501 message (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -115,156 +122,4 @@ class ApiResponse(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def code(self): - """Gets the code of this ApiResponse. # noqa: E501 - - Returns: - (int): The code of this ApiResponse. # noqa: E501 - """ - return self.__get_item('code') - - @code.setter - def code(self, value): - """Sets the code of this ApiResponse. # noqa: E501 - """ - return self.__set_item('code', value) - - @property - def type(self): - """Gets the type of this ApiResponse. # noqa: E501 - - Returns: - (str): The type of this ApiResponse. # noqa: E501 - """ - return self.__get_item('type') - - @type.setter - def type(self, value): - """Sets the type of this ApiResponse. # noqa: E501 - """ - return self.__set_item('type', value) - - @property - def message(self): - """Gets the message of this ApiResponse. # noqa: E501 - - Returns: - (str): The message of this ApiResponse. # noqa: E501 - """ - return self.__get_item('message') - - @message.setter - def message(self, value): - """Sets the message of this ApiResponse. # noqa: E501 - """ - return self.__set_item('message', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ApiResponse): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py index a2e3c7326a6..76165622532 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): allowed_values = { } - attribute_map = { - 'array_array_number': 'ArrayArrayNumber' # noqa: E501 - } - openapi_types = { 'array_array_number': ([[float]],), # noqa: E501 } @@ -80,10 +68,28 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'array_array_number': 'ArrayArrayNumber', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + """array_of_array_of_number_only.ArrayOfArrayOfNumberOnly - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): If omitted no type conversion is done. array_array_number ([[float]]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def array_array_number(self): - """Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - - Returns: - ([[float]]): The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - """ - return self.__get_item('array_array_number') - - @array_array_number.setter - def array_array_number(self, value): - """Sets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 - """ - return self.__set_item('array_array_number', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ArrayOfArrayOfNumberOnly): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py index c35c8e59631..165e0eed819 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class ArrayOfNumberOnly(ModelNormal): allowed_values = { } - attribute_map = { - 'array_number': 'ArrayNumber' # noqa: E501 - } - openapi_types = { 'array_number': ([float],), # noqa: E501 } @@ -80,10 +68,28 @@ class ArrayOfNumberOnly(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'array_number': 'ArrayNumber', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ArrayOfNumberOnly - a model defined in OpenAPI + """array_of_number_only.ArrayOfNumberOnly - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class ArrayOfNumberOnly(ModelNormal): If omitted no type conversion is done. array_number ([float]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class ArrayOfNumberOnly(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def array_number(self): - """Gets the array_number of this ArrayOfNumberOnly. # noqa: E501 - - Returns: - ([float]): The array_number of this ArrayOfNumberOnly. # noqa: E501 - """ - return self.__get_item('array_number') - - @array_number.setter - def array_number(self, value): - """Sets the array_number of this ArrayOfNumberOnly. # noqa: E501 - """ - return self.__set_item('array_number', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ArrayOfNumberOnly): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_test.py b/samples/client/petstore/python-experimental/petstore_api/models/array_test.py index cc52f04d318..72418960f57 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_test.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.read_only_first import ReadOnlyFirst +try: + from petstore_api.models import read_only_first +except ImportError: + read_only_first = sys.modules['petstore_api.models.read_only_first'] class ArrayTest(ModelNormal): @@ -68,16 +63,10 @@ class ArrayTest(ModelNormal): allowed_values = { } - attribute_map = { - 'array_of_string': 'array_of_string', # noqa: E501 - 'array_array_of_integer': 'array_array_of_integer', # noqa: E501 - 'array_array_of_model': 'array_array_of_model' # noqa: E501 - } - openapi_types = { 'array_of_string': ([str],), # noqa: E501 'array_array_of_integer': ([[int]],), # noqa: E501 - 'array_array_of_model': ([[ReadOnlyFirst]],), # noqa: E501 + 'array_array_of_model': ([[read_only_first.ReadOnlyFirst]],), # noqa: E501 } validations = { @@ -85,10 +74,30 @@ class ArrayTest(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'array_of_string': 'array_of_string', # noqa: E501 + 'array_array_of_integer': 'array_array_of_integer', # noqa: E501 + 'array_array_of_model': 'array_array_of_model', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ArrayTest - a model defined in OpenAPI + """array_test.ArrayTest - a model defined in OpenAPI Keyword Args: @@ -107,8 +116,9 @@ class ArrayTest(ModelNormal): If omitted no type conversion is done. array_of_string ([str]): [optional] # noqa: E501 array_array_of_integer ([[int]]): [optional] # noqa: E501 - array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + array_array_of_model ([[read_only_first.ReadOnlyFirst]]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -116,156 +126,4 @@ class ArrayTest(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def array_of_string(self): - """Gets the array_of_string of this ArrayTest. # noqa: E501 - - Returns: - ([str]): The array_of_string of this ArrayTest. # noqa: E501 - """ - return self.__get_item('array_of_string') - - @array_of_string.setter - def array_of_string(self, value): - """Sets the array_of_string of this ArrayTest. # noqa: E501 - """ - return self.__set_item('array_of_string', value) - - @property - def array_array_of_integer(self): - """Gets the array_array_of_integer of this ArrayTest. # noqa: E501 - - Returns: - ([[int]]): The array_array_of_integer of this ArrayTest. # noqa: E501 - """ - return self.__get_item('array_array_of_integer') - - @array_array_of_integer.setter - def array_array_of_integer(self, value): - """Sets the array_array_of_integer of this ArrayTest. # noqa: E501 - """ - return self.__set_item('array_array_of_integer', value) - - @property - def array_array_of_model(self): - """Gets the array_array_of_model of this ArrayTest. # noqa: E501 - - Returns: - ([[ReadOnlyFirst]]): The array_array_of_model of this ArrayTest. # noqa: E501 - """ - return self.__get_item('array_array_of_model') - - @array_array_of_model.setter - def array_array_of_model(self, value): - """Sets the array_array_of_model of this ArrayTest. # noqa: E501 - """ - return self.__set_item('array_array_of_model', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ArrayTest): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py b/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py index 9134f5e4251..a25472b19da 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,15 +59,6 @@ class Capitalization(ModelNormal): allowed_values = { } - attribute_map = { - 'small_camel': 'smallCamel', # noqa: E501 - 'capital_camel': 'CapitalCamel', # noqa: E501 - 'small_snake': 'small_Snake', # noqa: E501 - 'capital_snake': 'Capital_Snake', # noqa: E501 - 'sca_eth_flow_points': 'SCA_ETH_Flow_Points', # noqa: E501 - 'att_name': 'ATT_NAME' # noqa: E501 - } - openapi_types = { 'small_camel': (str,), # noqa: E501 'capital_camel': (str,), # noqa: E501 @@ -90,10 +73,33 @@ class Capitalization(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'small_camel': 'smallCamel', # noqa: E501 + 'capital_camel': 'CapitalCamel', # noqa: E501 + 'small_snake': 'small_Snake', # noqa: E501 + 'capital_snake': 'Capital_Snake', # noqa: E501 + 'sca_eth_flow_points': 'SCA_ETH_Flow_Points', # noqa: E501 + 'att_name': 'ATT_NAME', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Capitalization - a model defined in OpenAPI + """capitalization.Capitalization - a model defined in OpenAPI Keyword Args: @@ -117,6 +123,7 @@ class Capitalization(ModelNormal): sca_eth_flow_points (str): [optional] # noqa: E501 att_name (str): Name of the pet . [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -124,203 +131,4 @@ class Capitalization(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def small_camel(self): - """Gets the small_camel of this Capitalization. # noqa: E501 - - Returns: - (str): The small_camel of this Capitalization. # noqa: E501 - """ - return self.__get_item('small_camel') - - @small_camel.setter - def small_camel(self, value): - """Sets the small_camel of this Capitalization. # noqa: E501 - """ - return self.__set_item('small_camel', value) - - @property - def capital_camel(self): - """Gets the capital_camel of this Capitalization. # noqa: E501 - - Returns: - (str): The capital_camel of this Capitalization. # noqa: E501 - """ - return self.__get_item('capital_camel') - - @capital_camel.setter - def capital_camel(self, value): - """Sets the capital_camel of this Capitalization. # noqa: E501 - """ - return self.__set_item('capital_camel', value) - - @property - def small_snake(self): - """Gets the small_snake of this Capitalization. # noqa: E501 - - Returns: - (str): The small_snake of this Capitalization. # noqa: E501 - """ - return self.__get_item('small_snake') - - @small_snake.setter - def small_snake(self, value): - """Sets the small_snake of this Capitalization. # noqa: E501 - """ - return self.__set_item('small_snake', value) - - @property - def capital_snake(self): - """Gets the capital_snake of this Capitalization. # noqa: E501 - - Returns: - (str): The capital_snake of this Capitalization. # noqa: E501 - """ - return self.__get_item('capital_snake') - - @capital_snake.setter - def capital_snake(self, value): - """Sets the capital_snake of this Capitalization. # noqa: E501 - """ - return self.__set_item('capital_snake', value) - - @property - def sca_eth_flow_points(self): - """Gets the sca_eth_flow_points of this Capitalization. # noqa: E501 - - Returns: - (str): The sca_eth_flow_points of this Capitalization. # noqa: E501 - """ - return self.__get_item('sca_eth_flow_points') - - @sca_eth_flow_points.setter - def sca_eth_flow_points(self, value): - """Sets the sca_eth_flow_points of this Capitalization. # noqa: E501 - """ - return self.__set_item('sca_eth_flow_points', value) - - @property - def att_name(self): - """Gets the att_name of this Capitalization. # noqa: E501 - Name of the pet # noqa: E501 - - Returns: - (str): The att_name of this Capitalization. # noqa: E501 - """ - return self.__get_item('att_name') - - @att_name.setter - def att_name(self, value): - """Sets the att_name of this Capitalization. # noqa: E501 - Name of the pet # noqa: E501 - """ - return self.__set_item('att_name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Capitalization): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/cat.py b/samples/client/petstore/python-experimental/petstore_api/models/cat.py index 40508dd3ce7..fc9ab76fbfd 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/cat.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/cat.py @@ -10,35 +10,35 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) +try: + from petstore_api.models import animal +except ImportError: + animal = sys.modules['petstore_api.models.animal'] +try: + from petstore_api.models import cat_all_of +except ImportError: + cat_all_of = sys.modules['petstore_api.models.cat_all_of'] -class Cat(ModelNormal): +class Cat(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -67,16 +67,10 @@ class Cat(ModelNormal): allowed_values = { } - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'color': 'color', # noqa: E501 - 'declawed': 'declawed' # noqa: E501 - } - openapi_types = { 'class_name': (str,), # noqa: E501 - 'color': (str,), # noqa: E501 'declawed': (bool,), # noqa: E501 + 'color': (str,), # noqa: E501 } validations = { @@ -84,10 +78,29 @@ class Cat(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'declawed': 'declawed', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Cat - a model defined in OpenAPI + """cat.Cat - a model defined in OpenAPI Args: class_name (str): @@ -109,164 +122,49 @@ class Cat(ModelNormal): declawed (bool): [optional] # noqa: E501 color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('class_name', class_name) + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'class_name': class_name, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.class_name = class_name for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) + setattr(self, var_name, var_value) - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def class_name(self): - """Gets the class_name of this Cat. # noqa: E501 - - Returns: - (str): The class_name of this Cat. # noqa: E501 - """ - return self.__get_item('class_name') - - @class_name.setter - def class_name(self, value): - """Sets the class_name of this Cat. # noqa: E501 - """ - return self.__set_item('class_name', value) - - @property - def color(self): - """Gets the color of this Cat. # noqa: E501 - - Returns: - (str): The color of this Cat. # noqa: E501 - """ - return self.__get_item('color') - - @color.setter - def color(self, value): - """Sets the color of this Cat. # noqa: E501 - """ - return self.__set_item('color', value) - - @property - def declawed(self): - """Gets the declawed of this Cat. # noqa: E501 - - Returns: - (bool): The declawed of this Cat. # noqa: E501 - """ - return self.__get_item('declawed') - - @declawed.setter - def declawed(self, value): - """Sets the declawed of this Cat. # noqa: E501 - """ - return self.__set_item('declawed', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Cat): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + animal.Animal, + cat_all_of.CatAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py index cb1f0d815a0..4e4c87e90d4 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class CatAllOf(ModelNormal): allowed_values = { } - attribute_map = { - 'declawed': 'declawed' # noqa: E501 - } - openapi_types = { 'declawed': (bool,), # noqa: E501 } @@ -80,10 +68,28 @@ class CatAllOf(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'declawed': 'declawed', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """CatAllOf - a model defined in OpenAPI + """cat_all_of.CatAllOf - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class CatAllOf(ModelNormal): If omitted no type conversion is done. declawed (bool): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class CatAllOf(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def declawed(self): - """Gets the declawed of this CatAllOf. # noqa: E501 - - Returns: - (bool): The declawed of this CatAllOf. # noqa: E501 - """ - return self.__get_item('declawed') - - @declawed.setter - def declawed(self, value): - """Sets the declawed of this CatAllOf. # noqa: E501 - """ - return self.__set_item('declawed', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, CatAllOf): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/category.py b/samples/client/petstore/python-experimental/petstore_api/models/category.py index ca367ad9c3d..08c3e8aad96 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/category.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/category.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,14 +59,9 @@ class Category(ModelNormal): allowed_values = { } - attribute_map = { - 'id': 'id', # noqa: E501 - 'name': 'name' # noqa: E501 - } - openapi_types = { - 'id': (int,), # noqa: E501 'name': (str,), # noqa: E501 + 'id': (int,), # noqa: E501 } validations = { @@ -82,10 +69,29 @@ class Category(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + 'id': 'id', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, name='default-name', _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Category - a model defined in OpenAPI + """category.Category - a model defined in OpenAPI Args: @@ -106,149 +112,13 @@ class Category(ModelNormal): If omitted no type conversion is done. id (int): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('name', name) + self.name = name for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def id(self): - """Gets the id of this Category. # noqa: E501 - - Returns: - (int): The id of this Category. # noqa: E501 - """ - return self.__get_item('id') - - @id.setter - def id(self, value): - """Sets the id of this Category. # noqa: E501 - """ - return self.__set_item('id', value) - - @property - def name(self): - """Gets the name of this Category. # noqa: E501 - - Returns: - (str): The name of this Category. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this Category. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Category): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child.py b/samples/client/petstore/python-experimental/petstore_api/models/child.py new file mode 100644 index 00000000000..7e5e332f008 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child.py @@ -0,0 +1,167 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import child_all_of +except ImportError: + child_all_of = sys.modules['petstore_api.models.child_all_of'] +try: + from petstore_api.models import parent +except ImportError: + parent = sys.modules['petstore_api.models.parent'] + + +class Child(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'radio_waves': (bool,), # noqa: E501 + 'tele_vision': (bool,), # noqa: E501 + 'inter_net': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + 'tele_vision': 'teleVision', # noqa: E501 + 'inter_net': 'interNet', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child.Child - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + child_all_of.ChildAllOf, + parent.Parent, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py new file mode 100644 index 00000000000..3cb28139b17 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class ChildAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'inter_net': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'inter_net': 'interNet', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_all_of.ChildAllOf - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + inter_net (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py b/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py new file mode 100644 index 00000000000..58c0318faf0 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py @@ -0,0 +1,167 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import child_cat_all_of +except ImportError: + child_cat_all_of = sys.modules['petstore_api.models.child_cat_all_of'] +try: + from petstore_api.models import parent_pet +except ImportError: + parent_pet = sys.modules['petstore_api.models.parent_pet'] + + +class ChildCat(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'pet_type': (str,), # noqa: E501 + 'name': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'name': 'name', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_cat.ChildCat - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + name (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'pet_type': pet_type, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.pet_type = pet_type + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + child_cat_all_of.ChildCatAllOf, + parent_pet.ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py new file mode 100644 index 00000000000..de70d839cf2 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class ChildCatAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'name': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_cat_all_of.ChildCatAllOf - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + name (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py b/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py new file mode 100644 index 00000000000..450e6983fca --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py @@ -0,0 +1,167 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import child_dog_all_of +except ImportError: + child_dog_all_of = sys.modules['petstore_api.models.child_dog_all_of'] +try: + from petstore_api.models import parent_pet +except ImportError: + parent_pet = sys.modules['petstore_api.models.parent_pet'] + + +class ChildDog(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'pet_type': (str,), # noqa: E501 + 'bark': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'bark': 'bark', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_dog.ChildDog - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + bark (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'pet_type': pet_type, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.pet_type = pet_type + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + child_dog_all_of.ChildDogAllOf, + parent_pet.ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py new file mode 100644 index 00000000000..37d900f2c2b --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class ChildDogAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'bark': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'bark': 'bark', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_dog_all_of.ChildDogAllOf - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + bark (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py new file mode 100644 index 00000000000..169d05b5136 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py @@ -0,0 +1,167 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import child_lizard_all_of +except ImportError: + child_lizard_all_of = sys.modules['petstore_api.models.child_lizard_all_of'] +try: + from petstore_api.models import parent_pet +except ImportError: + parent_pet = sys.modules['petstore_api.models.parent_pet'] + + +class ChildLizard(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'pet_type': (str,), # noqa: E501 + 'loves_rocks': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'loves_rocks': 'lovesRocks', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_lizard.ChildLizard - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + loves_rocks (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'pet_type': pet_type, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.pet_type = pet_type + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + child_lizard_all_of.ChildLizardAllOf, + parent_pet.ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py new file mode 100644 index 00000000000..6b6f8d99279 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class ChildLizardAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'loves_rocks': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'loves_rocks': 'lovesRocks', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """child_lizard_all_of.ChildLizardAllOf - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + loves_rocks (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/class_model.py b/samples/client/petstore/python-experimental/petstore_api/models/class_model.py index b44cdb80aae..4f6fd3bca5e 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/class_model.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class ClassModel(ModelNormal): allowed_values = { } - attribute_map = { - '_class': '_class' # noqa: E501 - } - openapi_types = { '_class': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class ClassModel(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + '_class': '_class', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ClassModel - a model defined in OpenAPI + """class_model.ClassModel - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class ClassModel(ModelNormal): If omitted no type conversion is done. _class (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class ClassModel(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def _class(self): - """Gets the _class of this ClassModel. # noqa: E501 - - Returns: - (str): The _class of this ClassModel. # noqa: E501 - """ - return self.__get_item('_class') - - @_class.setter - def _class(self, value): - """Sets the _class of this ClassModel. # noqa: E501 - """ - return self.__set_item('_class', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ClassModel): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/client.py b/samples/client/petstore/python-experimental/petstore_api/models/client.py index 5e1699a2196..398d1b7ce0d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/client.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/client.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class Client(ModelNormal): allowed_values = { } - attribute_map = { - 'client': 'client' # noqa: E501 - } - openapi_types = { 'client': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class Client(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'client': 'client', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Client - a model defined in OpenAPI + """client.Client - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class Client(ModelNormal): If omitted no type conversion is done. client (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class Client(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def client(self): - """Gets the client of this Client. # noqa: E501 - - Returns: - (str): The client of this Client. # noqa: E501 - """ - return self.__get_item('client') - - @client.setter - def client(self, value): - """Sets the client of this Client. # noqa: E501 - """ - return self.__set_item('client', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Client): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/dog.py b/samples/client/petstore/python-experimental/petstore_api/models/dog.py index bac013b867d..f27e858b4c1 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/dog.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/dog.py @@ -10,35 +10,35 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) +try: + from petstore_api.models import animal +except ImportError: + animal = sys.modules['petstore_api.models.animal'] +try: + from petstore_api.models import dog_all_of +except ImportError: + dog_all_of = sys.modules['petstore_api.models.dog_all_of'] -class Dog(ModelNormal): +class Dog(ModelComposed): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -67,16 +67,10 @@ class Dog(ModelNormal): allowed_values = { } - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'color': 'color', # noqa: E501 - 'breed': 'breed' # noqa: E501 - } - openapi_types = { 'class_name': (str,), # noqa: E501 - 'color': (str,), # noqa: E501 'breed': (str,), # noqa: E501 + 'color': (str,), # noqa: E501 } validations = { @@ -84,10 +78,29 @@ class Dog(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'breed': 'breed', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Dog - a model defined in OpenAPI + """dog.Dog - a model defined in OpenAPI Args: class_name (str): @@ -109,164 +122,49 @@ class Dog(ModelNormal): breed (str): [optional] # noqa: E501 color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('class_name', class_name) + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'class_name': class_name, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.class_name = class_name for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) + setattr(self, var_name, var_value) - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def class_name(self): - """Gets the class_name of this Dog. # noqa: E501 - - Returns: - (str): The class_name of this Dog. # noqa: E501 - """ - return self.__get_item('class_name') - - @class_name.setter - def class_name(self, value): - """Sets the class_name of this Dog. # noqa: E501 - """ - return self.__set_item('class_name', value) - - @property - def color(self): - """Gets the color of this Dog. # noqa: E501 - - Returns: - (str): The color of this Dog. # noqa: E501 - """ - return self.__get_item('color') - - @color.setter - def color(self, value): - """Sets the color of this Dog. # noqa: E501 - """ - return self.__set_item('color', value) - - @property - def breed(self): - """Gets the breed of this Dog. # noqa: E501 - - Returns: - (str): The breed of this Dog. # noqa: E501 - """ - return self.__get_item('breed') - - @breed.setter - def breed(self, value): - """Sets the breed of this Dog. # noqa: E501 - """ - return self.__set_item('breed', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Dog): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + animal.Animal, + dog_all_of.DogAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py index 7d9a33bbe36..18e9270a4c6 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class DogAllOf(ModelNormal): allowed_values = { } - attribute_map = { - 'breed': 'breed' # noqa: E501 - } - openapi_types = { 'breed': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class DogAllOf(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'breed': 'breed', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """DogAllOf - a model defined in OpenAPI + """dog_all_of.DogAllOf - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class DogAllOf(ModelNormal): If omitted no type conversion is done. breed (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class DogAllOf(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def breed(self): - """Gets the breed of this DogAllOf. # noqa: E501 - - Returns: - (str): The breed of this DogAllOf. # noqa: E501 - """ - return self.__get_item('breed') - - @breed.setter - def breed(self, value): - """Sets the breed of this DogAllOf. # noqa: E501 - """ - return self.__set_item('breed', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, DogAllOf): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py index 477193e858f..167f573d452 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -75,11 +67,6 @@ class EnumArrays(ModelNormal): }, } - attribute_map = { - 'just_symbol': 'just_symbol', # noqa: E501 - 'array_enum': 'array_enum' # noqa: E501 - } - openapi_types = { 'just_symbol': (str,), # noqa: E501 'array_enum': ([str],), # noqa: E501 @@ -90,10 +77,29 @@ class EnumArrays(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'just_symbol': 'just_symbol', # noqa: E501 + 'array_enum': 'array_enum', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """EnumArrays - a model defined in OpenAPI + """enum_arrays.EnumArrays - a model defined in OpenAPI Keyword Args: @@ -113,6 +119,7 @@ class EnumArrays(ModelNormal): just_symbol (str): [optional] # noqa: E501 array_enum ([str]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -120,141 +127,4 @@ class EnumArrays(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def just_symbol(self): - """Gets the just_symbol of this EnumArrays. # noqa: E501 - - Returns: - (str): The just_symbol of this EnumArrays. # noqa: E501 - """ - return self.__get_item('just_symbol') - - @just_symbol.setter - def just_symbol(self, value): - """Sets the just_symbol of this EnumArrays. # noqa: E501 - """ - return self.__set_item('just_symbol', value) - - @property - def array_enum(self): - """Gets the array_enum of this EnumArrays. # noqa: E501 - - Returns: - ([str]): The array_enum of this EnumArrays. # noqa: E501 - """ - return self.__get_item('array_enum') - - @array_enum.setter - def array_enum(self, value): - """Sets the array_enum of this EnumArrays. # noqa: E501 - """ - return self.__set_item('array_enum', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, EnumArrays): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py index 0b3bca10a53..b80116abce1 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -77,10 +69,24 @@ class EnumClass(ModelSimple): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, value='-efg', _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """EnumClass - a model defined in OpenAPI + """enum_class.EnumClass - a model defined in OpenAPI Args: @@ -100,127 +106,13 @@ class EnumClass(ModelSimple): If passed, type conversion is attempted If omitted no type conversion is done. """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('value', value) + self.value = value for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def value(self): - """Gets the value of this EnumClass. # noqa: E501 - - Returns: - (str): The value of this EnumClass. # noqa: E501 - """ - return self.__get_item('value') - - @value.setter - def value(self, value): - """Sets the value of this EnumClass. # noqa: E501 - """ - return self.__set_item('value', value) - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, EnumClass): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py index 83f6d78c3f8..c7bef7cc320 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.outer_enum import OuterEnum +try: + from petstore_api.models import outer_enum +except ImportError: + outer_enum = sys.modules['petstore_api.models.outer_enum'] class EnumTest(ModelNormal): @@ -66,12 +61,12 @@ class EnumTest(ModelNormal): """ allowed_values = { - ('enum_string',): { + ('enum_string_required',): { 'UPPER': "UPPER", 'LOWER': "lower", 'EMPTY': "", }, - ('enum_string_required',): { + ('enum_string',): { 'UPPER': "UPPER", 'LOWER': "lower", 'EMPTY': "", @@ -86,20 +81,12 @@ class EnumTest(ModelNormal): }, } - attribute_map = { - 'enum_string': 'enum_string', # noqa: E501 - 'enum_string_required': 'enum_string_required', # noqa: E501 - 'enum_integer': 'enum_integer', # noqa: E501 - 'enum_number': 'enum_number', # noqa: E501 - 'outer_enum': 'outerEnum' # noqa: E501 - } - openapi_types = { - 'enum_string': (str,), # noqa: E501 'enum_string_required': (str,), # noqa: E501 + 'enum_string': (str,), # noqa: E501 'enum_integer': (int,), # noqa: E501 'enum_number': (float,), # noqa: E501 - 'outer_enum': (OuterEnum,), # noqa: E501 + 'outer_enum': (outer_enum.OuterEnum,), # noqa: E501 } validations = { @@ -107,10 +94,32 @@ class EnumTest(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'enum_string_required': 'enum_string_required', # noqa: E501 + 'enum_string': 'enum_string', # noqa: E501 + 'enum_integer': 'enum_integer', # noqa: E501 + 'enum_number': 'enum_number', # noqa: E501 + 'outer_enum': 'outerEnum', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, enum_string_required, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """EnumTest - a model defined in OpenAPI + """enum_test.EnumTest - a model defined in OpenAPI Args: enum_string_required (str): @@ -132,196 +141,15 @@ class EnumTest(ModelNormal): enum_string (str): [optional] # noqa: E501 enum_integer (int): [optional] # noqa: E501 enum_number (float): [optional] # noqa: E501 - outer_enum (OuterEnum): [optional] # noqa: E501 + outer_enum (outer_enum.OuterEnum): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('enum_string_required', enum_string_required) + self.enum_string_required = enum_string_required for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def enum_string(self): - """Gets the enum_string of this EnumTest. # noqa: E501 - - Returns: - (str): The enum_string of this EnumTest. # noqa: E501 - """ - return self.__get_item('enum_string') - - @enum_string.setter - def enum_string(self, value): - """Sets the enum_string of this EnumTest. # noqa: E501 - """ - return self.__set_item('enum_string', value) - - @property - def enum_string_required(self): - """Gets the enum_string_required of this EnumTest. # noqa: E501 - - Returns: - (str): The enum_string_required of this EnumTest. # noqa: E501 - """ - return self.__get_item('enum_string_required') - - @enum_string_required.setter - def enum_string_required(self, value): - """Sets the enum_string_required of this EnumTest. # noqa: E501 - """ - return self.__set_item('enum_string_required', value) - - @property - def enum_integer(self): - """Gets the enum_integer of this EnumTest. # noqa: E501 - - Returns: - (int): The enum_integer of this EnumTest. # noqa: E501 - """ - return self.__get_item('enum_integer') - - @enum_integer.setter - def enum_integer(self, value): - """Sets the enum_integer of this EnumTest. # noqa: E501 - """ - return self.__set_item('enum_integer', value) - - @property - def enum_number(self): - """Gets the enum_number of this EnumTest. # noqa: E501 - - Returns: - (float): The enum_number of this EnumTest. # noqa: E501 - """ - return self.__get_item('enum_number') - - @enum_number.setter - def enum_number(self, value): - """Sets the enum_number of this EnumTest. # noqa: E501 - """ - return self.__set_item('enum_number', value) - - @property - def outer_enum(self): - """Gets the outer_enum of this EnumTest. # noqa: E501 - - Returns: - (OuterEnum): The outer_enum of this EnumTest. # noqa: E501 - """ - return self.__get_item('outer_enum') - - @outer_enum.setter - def outer_enum(self, value): - """Sets the outer_enum of this EnumTest. # noqa: E501 - """ - return self.__set_item('outer_enum', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, EnumTest): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/file.py b/samples/client/petstore/python-experimental/petstore_api/models/file.py index 7da4e025a20..eb71f20abb3 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/file.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/file.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class File(ModelNormal): allowed_values = { } - attribute_map = { - 'source_uri': 'sourceURI' # noqa: E501 - } - openapi_types = { 'source_uri': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class File(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'source_uri': 'sourceURI', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """File - a model defined in OpenAPI + """file.File - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class File(ModelNormal): If omitted no type conversion is done. source_uri (str): Test capitalization. [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,128 +116,4 @@ class File(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def source_uri(self): - """Gets the source_uri of this File. # noqa: E501 - Test capitalization # noqa: E501 - - Returns: - (str): The source_uri of this File. # noqa: E501 - """ - return self.__get_item('source_uri') - - @source_uri.setter - def source_uri(self, value): - """Sets the source_uri of this File. # noqa: E501 - Test capitalization # noqa: E501 - """ - return self.__set_item('source_uri', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, File): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py index 5e0ca0498d9..b612ecf317c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.file import File +try: + from petstore_api.models import file +except ImportError: + file = sys.modules['petstore_api.models.file'] class FileSchemaTestClass(ModelNormal): @@ -68,14 +63,9 @@ class FileSchemaTestClass(ModelNormal): allowed_values = { } - attribute_map = { - 'file': 'file', # noqa: E501 - 'files': 'files' # noqa: E501 - } - openapi_types = { - 'file': (File,), # noqa: E501 - 'files': ([File],), # noqa: E501 + 'file': (file.File,), # noqa: E501 + 'files': ([file.File],), # noqa: E501 } validations = { @@ -83,10 +73,29 @@ class FileSchemaTestClass(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'file': 'file', # noqa: E501 + 'files': 'files', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """FileSchemaTestClass - a model defined in OpenAPI + """file_schema_test_class.FileSchemaTestClass - a model defined in OpenAPI Keyword Args: @@ -103,9 +112,10 @@ class FileSchemaTestClass(ModelNormal): deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. - file (File): [optional] # noqa: E501 - files ([File]): [optional] # noqa: E501 + file (file.File): [optional] # noqa: E501 + files ([file.File]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -113,141 +123,4 @@ class FileSchemaTestClass(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def file(self): - """Gets the file of this FileSchemaTestClass. # noqa: E501 - - Returns: - (File): The file of this FileSchemaTestClass. # noqa: E501 - """ - return self.__get_item('file') - - @file.setter - def file(self, value): - """Sets the file of this FileSchemaTestClass. # noqa: E501 - """ - return self.__set_item('file', value) - - @property - def files(self): - """Gets the files of this FileSchemaTestClass. # noqa: E501 - - Returns: - ([File]): The files of this FileSchemaTestClass. # noqa: E501 - """ - return self.__get_item('files') - - @files.setter - def files(self, value): - """Sets the files of this FileSchemaTestClass. # noqa: E501 - """ - return self.__set_item('files', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, FileSchemaTestClass): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/format_test.py b/samples/client/petstore/python-experimental/petstore_api/models/format_test.py index de33c15695b..7b455ece510 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/format_test.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,39 +59,36 @@ class FormatTest(ModelNormal): allowed_values = { } - attribute_map = { - 'integer': 'integer', # noqa: E501 - 'int32': 'int32', # noqa: E501 - 'int64': 'int64', # noqa: E501 - 'number': 'number', # noqa: E501 - 'float': 'float', # noqa: E501 - 'double': 'double', # noqa: E501 - 'string': 'string', # noqa: E501 - 'byte': 'byte', # noqa: E501 - 'binary': 'binary', # noqa: E501 - 'date': 'date', # noqa: E501 - 'date_time': 'dateTime', # noqa: E501 - 'uuid': 'uuid', # noqa: E501 - 'password': 'password' # noqa: E501 - } - openapi_types = { + 'number': (float,), # noqa: E501 + 'byte': (str,), # noqa: E501 + 'date': (date,), # noqa: E501 + 'password': (str,), # noqa: E501 'integer': (int,), # noqa: E501 'int32': (int,), # noqa: E501 'int64': (int,), # noqa: E501 - 'number': (float,), # noqa: E501 'float': (float,), # noqa: E501 'double': (float,), # noqa: E501 'string': (str,), # noqa: E501 - 'byte': (str,), # noqa: E501 'binary': (file_type,), # noqa: E501 - 'date': (date,), # noqa: E501 'date_time': (datetime,), # noqa: E501 'uuid': (str,), # noqa: E501 - 'password': (str,), # noqa: E501 } validations = { + ('number',): { + 'inclusive_maximum': 543.2, + 'inclusive_minimum': 32.1, + }, + ('byte',): { + 'regex': { + 'pattern': r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', # noqa: E501 + }, + }, + ('password',): { + 'max_length': 64, + 'min_length': 10, + }, ('integer',): { 'inclusive_maximum': 100, 'inclusive_minimum': 10, @@ -108,10 +97,6 @@ class FormatTest(ModelNormal): 'inclusive_maximum': 200, 'inclusive_minimum': 20, }, - ('number',): { - 'inclusive_maximum': 543.2, - 'inclusive_minimum': 32.1, - }, ('float',): { 'inclusive_maximum': 987.6, 'inclusive_minimum': 54.3, @@ -126,23 +111,44 @@ class FormatTest(ModelNormal): 'flags': (re.IGNORECASE) }, }, - ('byte',): { - 'regex': { - 'pattern': r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', # noqa: E501 - }, - }, - ('password',): { - 'max_length': 64, - 'min_length': 10, - }, } additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'number': 'number', # noqa: E501 + 'byte': 'byte', # noqa: E501 + 'date': 'date', # noqa: E501 + 'password': 'password', # noqa: E501 + 'integer': 'integer', # noqa: E501 + 'int32': 'int32', # noqa: E501 + 'int64': 'int64', # noqa: E501 + 'float': 'float', # noqa: E501 + 'double': 'double', # noqa: E501 + 'string': 'string', # noqa: E501 + 'binary': 'binary', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'uuid': 'uuid', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, number, byte, date, password, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """FormatTest - a model defined in OpenAPI + """format_test.FormatTest - a model defined in OpenAPI Args: number (float): @@ -174,317 +180,16 @@ class FormatTest(ModelNormal): date_time (datetime): [optional] # noqa: E501 uuid (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('number', number) - self.__set_item('byte', byte) - self.__set_item('date', date) - self.__set_item('password', password) + self.number = number + self.byte = byte + self.date = date + self.password = password for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def integer(self): - """Gets the integer of this FormatTest. # noqa: E501 - - Returns: - (int): The integer of this FormatTest. # noqa: E501 - """ - return self.__get_item('integer') - - @integer.setter - def integer(self, value): - """Sets the integer of this FormatTest. # noqa: E501 - """ - return self.__set_item('integer', value) - - @property - def int32(self): - """Gets the int32 of this FormatTest. # noqa: E501 - - Returns: - (int): The int32 of this FormatTest. # noqa: E501 - """ - return self.__get_item('int32') - - @int32.setter - def int32(self, value): - """Sets the int32 of this FormatTest. # noqa: E501 - """ - return self.__set_item('int32', value) - - @property - def int64(self): - """Gets the int64 of this FormatTest. # noqa: E501 - - Returns: - (int): The int64 of this FormatTest. # noqa: E501 - """ - return self.__get_item('int64') - - @int64.setter - def int64(self, value): - """Sets the int64 of this FormatTest. # noqa: E501 - """ - return self.__set_item('int64', value) - - @property - def number(self): - """Gets the number of this FormatTest. # noqa: E501 - - Returns: - (float): The number of this FormatTest. # noqa: E501 - """ - return self.__get_item('number') - - @number.setter - def number(self, value): - """Sets the number of this FormatTest. # noqa: E501 - """ - return self.__set_item('number', value) - - @property - def float(self): - """Gets the float of this FormatTest. # noqa: E501 - - Returns: - (float): The float of this FormatTest. # noqa: E501 - """ - return self.__get_item('float') - - @float.setter - def float(self, value): - """Sets the float of this FormatTest. # noqa: E501 - """ - return self.__set_item('float', value) - - @property - def double(self): - """Gets the double of this FormatTest. # noqa: E501 - - Returns: - (float): The double of this FormatTest. # noqa: E501 - """ - return self.__get_item('double') - - @double.setter - def double(self, value): - """Sets the double of this FormatTest. # noqa: E501 - """ - return self.__set_item('double', value) - - @property - def string(self): - """Gets the string of this FormatTest. # noqa: E501 - - Returns: - (str): The string of this FormatTest. # noqa: E501 - """ - return self.__get_item('string') - - @string.setter - def string(self, value): - """Sets the string of this FormatTest. # noqa: E501 - """ - return self.__set_item('string', value) - - @property - def byte(self): - """Gets the byte of this FormatTest. # noqa: E501 - - Returns: - (str): The byte of this FormatTest. # noqa: E501 - """ - return self.__get_item('byte') - - @byte.setter - def byte(self, value): - """Sets the byte of this FormatTest. # noqa: E501 - """ - return self.__set_item('byte', value) - - @property - def binary(self): - """Gets the binary of this FormatTest. # noqa: E501 - - Returns: - (file_type): The binary of this FormatTest. # noqa: E501 - """ - return self.__get_item('binary') - - @binary.setter - def binary(self, value): - """Sets the binary of this FormatTest. # noqa: E501 - """ - return self.__set_item('binary', value) - - @property - def date(self): - """Gets the date of this FormatTest. # noqa: E501 - - Returns: - (date): The date of this FormatTest. # noqa: E501 - """ - return self.__get_item('date') - - @date.setter - def date(self, value): - """Sets the date of this FormatTest. # noqa: E501 - """ - return self.__set_item('date', value) - - @property - def date_time(self): - """Gets the date_time of this FormatTest. # noqa: E501 - - Returns: - (datetime): The date_time of this FormatTest. # noqa: E501 - """ - return self.__get_item('date_time') - - @date_time.setter - def date_time(self, value): - """Sets the date_time of this FormatTest. # noqa: E501 - """ - return self.__set_item('date_time', value) - - @property - def uuid(self): - """Gets the uuid of this FormatTest. # noqa: E501 - - Returns: - (str): The uuid of this FormatTest. # noqa: E501 - """ - return self.__get_item('uuid') - - @uuid.setter - def uuid(self, value): - """Sets the uuid of this FormatTest. # noqa: E501 - """ - return self.__set_item('uuid', value) - - @property - def password(self): - """Gets the password of this FormatTest. # noqa: E501 - - Returns: - (str): The password of this FormatTest. # noqa: E501 - """ - return self.__get_item('password') - - @password.setter - def password(self, value): - """Sets the password of this FormatTest. # noqa: E501 - """ - return self.__set_item('password', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, FormatTest): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py b/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py new file mode 100644 index 00000000000..26bae108ad1 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class Grandparent(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'radio_waves': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """grandparent.Grandparent - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + radio_waves (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py b/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py new file mode 100644 index 00000000000..5d99b80c162 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class GrandparentAnimal(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'pet_type': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """grandparent_animal.GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + self.pet_type = pet_type + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py index ecf201d21e8..593a6280d3d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,11 +59,6 @@ class HasOnlyReadOnly(ModelNormal): allowed_values = { } - attribute_map = { - 'bar': 'bar', # noqa: E501 - 'foo': 'foo' # noqa: E501 - } - openapi_types = { 'bar': (str,), # noqa: E501 'foo': (str,), # noqa: E501 @@ -82,10 +69,29 @@ class HasOnlyReadOnly(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'foo': 'foo', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """HasOnlyReadOnly - a model defined in OpenAPI + """has_only_read_only.HasOnlyReadOnly - a model defined in OpenAPI Keyword Args: @@ -105,6 +111,7 @@ class HasOnlyReadOnly(ModelNormal): bar (str): [optional] # noqa: E501 foo (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -112,141 +119,4 @@ class HasOnlyReadOnly(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def bar(self): - """Gets the bar of this HasOnlyReadOnly. # noqa: E501 - - Returns: - (str): The bar of this HasOnlyReadOnly. # noqa: E501 - """ - return self.__get_item('bar') - - @bar.setter - def bar(self, value): - """Sets the bar of this HasOnlyReadOnly. # noqa: E501 - """ - return self.__set_item('bar', value) - - @property - def foo(self): - """Gets the foo of this HasOnlyReadOnly. # noqa: E501 - - Returns: - (str): The foo of this HasOnlyReadOnly. # noqa: E501 - """ - return self.__get_item('foo') - - @foo.setter - def foo(self, value): - """Sets the foo of this HasOnlyReadOnly. # noqa: E501 - """ - return self.__set_item('foo', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, HasOnlyReadOnly): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/list.py b/samples/client/petstore/python-experimental/petstore_api/models/list.py index 79ff6c81bed..362ac90e2c9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/list.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/list.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class List(ModelNormal): allowed_values = { } - attribute_map = { - '_123_list': '123-list' # noqa: E501 - } - openapi_types = { '_123_list': (str,), # noqa: E501 } @@ -80,10 +68,28 @@ class List(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + '_123_list': '123-list', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """List - a model defined in OpenAPI + """list.List - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class List(ModelNormal): If omitted no type conversion is done. _123_list (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class List(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def _123_list(self): - """Gets the _123_list of this List. # noqa: E501 - - Returns: - (str): The _123_list of this List. # noqa: E501 - """ - return self.__get_item('_123_list') - - @_123_list.setter - def _123_list(self, value): - """Sets the _123_list of this List. # noqa: E501 - """ - return self.__set_item('_123_list', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, List): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/map_test.py b/samples/client/petstore/python-experimental/petstore_api/models/map_test.py index 84b07abdcc8..475332634ab 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/map_test.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.string_boolean_map import StringBooleanMap +try: + from petstore_api.models import string_boolean_map +except ImportError: + string_boolean_map = sys.modules['petstore_api.models.string_boolean_map'] class MapTest(ModelNormal): @@ -72,18 +67,11 @@ class MapTest(ModelNormal): }, } - attribute_map = { - 'map_map_of_string': 'map_map_of_string', # noqa: E501 - 'map_of_enum_string': 'map_of_enum_string', # noqa: E501 - 'direct_map': 'direct_map', # noqa: E501 - 'indirect_map': 'indirect_map' # noqa: E501 - } - openapi_types = { 'map_map_of_string': ({str: ({str: (str,)},)},), # noqa: E501 'map_of_enum_string': ({str: (str,)},), # noqa: E501 'direct_map': ({str: (bool,)},), # noqa: E501 - 'indirect_map': (StringBooleanMap,), # noqa: E501 + 'indirect_map': (string_boolean_map.StringBooleanMap,), # noqa: E501 } validations = { @@ -91,10 +79,31 @@ class MapTest(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'map_map_of_string': 'map_map_of_string', # noqa: E501 + 'map_of_enum_string': 'map_of_enum_string', # noqa: E501 + 'direct_map': 'direct_map', # noqa: E501 + 'indirect_map': 'indirect_map', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """MapTest - a model defined in OpenAPI + """map_test.MapTest - a model defined in OpenAPI Keyword Args: @@ -114,8 +123,9 @@ class MapTest(ModelNormal): map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 direct_map ({str: (bool,)}): [optional] # noqa: E501 - indirect_map (StringBooleanMap): [optional] # noqa: E501 + indirect_map (string_boolean_map.StringBooleanMap): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -123,171 +133,4 @@ class MapTest(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def map_map_of_string(self): - """Gets the map_map_of_string of this MapTest. # noqa: E501 - - Returns: - ({str: ({str: (str,)},)}): The map_map_of_string of this MapTest. # noqa: E501 - """ - return self.__get_item('map_map_of_string') - - @map_map_of_string.setter - def map_map_of_string(self, value): - """Sets the map_map_of_string of this MapTest. # noqa: E501 - """ - return self.__set_item('map_map_of_string', value) - - @property - def map_of_enum_string(self): - """Gets the map_of_enum_string of this MapTest. # noqa: E501 - - Returns: - ({str: (str,)}): The map_of_enum_string of this MapTest. # noqa: E501 - """ - return self.__get_item('map_of_enum_string') - - @map_of_enum_string.setter - def map_of_enum_string(self, value): - """Sets the map_of_enum_string of this MapTest. # noqa: E501 - """ - return self.__set_item('map_of_enum_string', value) - - @property - def direct_map(self): - """Gets the direct_map of this MapTest. # noqa: E501 - - Returns: - ({str: (bool,)}): The direct_map of this MapTest. # noqa: E501 - """ - return self.__get_item('direct_map') - - @direct_map.setter - def direct_map(self, value): - """Sets the direct_map of this MapTest. # noqa: E501 - """ - return self.__set_item('direct_map', value) - - @property - def indirect_map(self): - """Gets the indirect_map of this MapTest. # noqa: E501 - - Returns: - (StringBooleanMap): The indirect_map of this MapTest. # noqa: E501 - """ - return self.__get_item('indirect_map') - - @indirect_map.setter - def indirect_map(self, value): - """Sets the indirect_map of this MapTest. # noqa: E501 - """ - return self.__set_item('indirect_map', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, MapTest): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py index a8f9efb4297..a88a56b5cf5 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.animal import Animal +try: + from petstore_api.models import animal +except ImportError: + animal = sys.modules['petstore_api.models.animal'] class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): @@ -68,16 +63,10 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): allowed_values = { } - attribute_map = { - 'uuid': 'uuid', # noqa: E501 - 'date_time': 'dateTime', # noqa: E501 - 'map': 'map' # noqa: E501 - } - openapi_types = { 'uuid': (str,), # noqa: E501 'date_time': (datetime,), # noqa: E501 - 'map': ({str: (Animal,)},), # noqa: E501 + 'map': ({str: (animal.Animal,)},), # noqa: E501 } validations = { @@ -85,10 +74,30 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'uuid': 'uuid', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'map': 'map', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + """mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI Keyword Args: @@ -107,8 +116,9 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): If omitted no type conversion is done. uuid (str): [optional] # noqa: E501 date_time (datetime): [optional] # noqa: E501 - map ({str: (Animal,)}): [optional] # noqa: E501 + map ({str: (animal.Animal,)}): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -116,156 +126,4 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def uuid(self): - """Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - - Returns: - (str): The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('uuid') - - @uuid.setter - def uuid(self, value): - """Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('uuid', value) - - @property - def date_time(self): - """Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - - Returns: - (datetime): The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('date_time') - - @date_time.setter - def date_time(self, value): - """Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('date_time', value) - - @property - def map(self): - """Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - - Returns: - ({str: (Animal,)}): The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__get_item('map') - - @map.setter - def map(self, value): - """Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 - """ - return self.__set_item('map', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py b/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py index 4bb72561e84..1fabb5e9b50 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,11 +59,6 @@ class Model200Response(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name', # noqa: E501 - '_class': 'class' # noqa: E501 - } - openapi_types = { 'name': (int,), # noqa: E501 '_class': (str,), # noqa: E501 @@ -82,10 +69,29 @@ class Model200Response(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + '_class': 'class', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Model200Response - a model defined in OpenAPI + """model200_response.Model200Response - a model defined in OpenAPI Keyword Args: @@ -105,6 +111,7 @@ class Model200Response(ModelNormal): name (int): [optional] # noqa: E501 _class (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -112,141 +119,4 @@ class Model200Response(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this Model200Response. # noqa: E501 - - Returns: - (int): The name of this Model200Response. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this Model200Response. # noqa: E501 - """ - return self.__set_item('name', value) - - @property - def _class(self): - """Gets the _class of this Model200Response. # noqa: E501 - - Returns: - (str): The _class of this Model200Response. # noqa: E501 - """ - return self.__get_item('_class') - - @_class.setter - def _class(self, value): - """Sets the _class of this Model200Response. # noqa: E501 - """ - return self.__set_item('_class', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Model200Response): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/model_return.py b/samples/client/petstore/python-experimental/petstore_api/models/model_return.py index 1ca322750bf..3466f9d2e69 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/model_return.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class ModelReturn(ModelNormal): allowed_values = { } - attribute_map = { - '_return': 'return' # noqa: E501 - } - openapi_types = { '_return': (int,), # noqa: E501 } @@ -80,10 +68,28 @@ class ModelReturn(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + '_return': 'return', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ModelReturn - a model defined in OpenAPI + """model_return.ModelReturn - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class ModelReturn(ModelNormal): If omitted no type conversion is done. _return (int): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class ModelReturn(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def _return(self): - """Gets the _return of this ModelReturn. # noqa: E501 - - Returns: - (int): The _return of this ModelReturn. # noqa: E501 - """ - return self.__get_item('_return') - - @_return.setter - def _return(self, value): - """Sets the _return of this ModelReturn. # noqa: E501 - """ - return self.__set_item('_return', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelReturn): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/name.py b/samples/client/petstore/python-experimental/petstore_api/models/name.py index b4c205ae08c..39f9a4719da 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/name.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/name.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,13 +59,6 @@ class Name(ModelNormal): allowed_values = { } - attribute_map = { - 'name': 'name', # noqa: E501 - 'snake_case': 'snake_case', # noqa: E501 - '_property': 'property', # noqa: E501 - '_123_number': '123Number' # noqa: E501 - } - openapi_types = { 'name': (int,), # noqa: E501 'snake_case': (int,), # noqa: E501 @@ -86,10 +71,31 @@ class Name(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + 'snake_case': 'snake_case', # noqa: E501 + '_property': 'property', # noqa: E501 + '_123_number': '123Number', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Name - a model defined in OpenAPI + """name.Name - a model defined in OpenAPI Args: name (int): @@ -112,179 +118,13 @@ class Name(ModelNormal): _property (str): [optional] # noqa: E501 _123_number (int): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('name', name) + self.name = name for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def name(self): - """Gets the name of this Name. # noqa: E501 - - Returns: - (int): The name of this Name. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this Name. # noqa: E501 - """ - return self.__set_item('name', value) - - @property - def snake_case(self): - """Gets the snake_case of this Name. # noqa: E501 - - Returns: - (int): The snake_case of this Name. # noqa: E501 - """ - return self.__get_item('snake_case') - - @snake_case.setter - def snake_case(self, value): - """Sets the snake_case of this Name. # noqa: E501 - """ - return self.__set_item('snake_case', value) - - @property - def _property(self): - """Gets the _property of this Name. # noqa: E501 - - Returns: - (str): The _property of this Name. # noqa: E501 - """ - return self.__get_item('_property') - - @_property.setter - def _property(self, value): - """Sets the _property of this Name. # noqa: E501 - """ - return self.__set_item('_property', value) - - @property - def _123_number(self): - """Gets the _123_number of this Name. # noqa: E501 - - Returns: - (int): The _123_number of this Name. # noqa: E501 - """ - return self.__get_item('_123_number') - - @_123_number.setter - def _123_number(self, value): - """Sets the _123_number of this Name. # noqa: E501 - """ - return self.__set_item('_123_number', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Name): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/number_only.py index 0761b3d3e32..96c03cef11d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/number_only.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class NumberOnly(ModelNormal): allowed_values = { } - attribute_map = { - 'just_number': 'JustNumber' # noqa: E501 - } - openapi_types = { 'just_number': (float,), # noqa: E501 } @@ -80,10 +68,28 @@ class NumberOnly(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'just_number': 'JustNumber', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """NumberOnly - a model defined in OpenAPI + """number_only.NumberOnly - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class NumberOnly(ModelNormal): If omitted no type conversion is done. just_number (float): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class NumberOnly(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def just_number(self): - """Gets the just_number of this NumberOnly. # noqa: E501 - - Returns: - (float): The just_number of this NumberOnly. # noqa: E501 - """ - return self.__get_item('just_number') - - @just_number.setter - def just_number(self, value): - """Sets the just_number of this NumberOnly. # noqa: E501 - """ - return self.__set_item('just_number', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, NumberOnly): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/order.py b/samples/client/petstore/python-experimental/petstore_api/models/order.py index 64c84902aba..ad4e10f0b04 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/order.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/order.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -72,15 +64,6 @@ class Order(ModelNormal): }, } - attribute_map = { - 'id': 'id', # noqa: E501 - 'pet_id': 'petId', # noqa: E501 - 'quantity': 'quantity', # noqa: E501 - 'ship_date': 'shipDate', # noqa: E501 - 'status': 'status', # noqa: E501 - 'complete': 'complete' # noqa: E501 - } - openapi_types = { 'id': (int,), # noqa: E501 'pet_id': (int,), # noqa: E501 @@ -95,10 +78,33 @@ class Order(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'id': 'id', # noqa: E501 + 'pet_id': 'petId', # noqa: E501 + 'quantity': 'quantity', # noqa: E501 + 'ship_date': 'shipDate', # noqa: E501 + 'status': 'status', # noqa: E501 + 'complete': 'complete', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Order - a model defined in OpenAPI + """order.Order - a model defined in OpenAPI Keyword Args: @@ -122,6 +128,7 @@ class Order(ModelNormal): status (str): Order Status. [optional] # noqa: E501 complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -129,203 +136,4 @@ class Order(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def id(self): - """Gets the id of this Order. # noqa: E501 - - Returns: - (int): The id of this Order. # noqa: E501 - """ - return self.__get_item('id') - - @id.setter - def id(self, value): - """Sets the id of this Order. # noqa: E501 - """ - return self.__set_item('id', value) - - @property - def pet_id(self): - """Gets the pet_id of this Order. # noqa: E501 - - Returns: - (int): The pet_id of this Order. # noqa: E501 - """ - return self.__get_item('pet_id') - - @pet_id.setter - def pet_id(self, value): - """Sets the pet_id of this Order. # noqa: E501 - """ - return self.__set_item('pet_id', value) - - @property - def quantity(self): - """Gets the quantity of this Order. # noqa: E501 - - Returns: - (int): The quantity of this Order. # noqa: E501 - """ - return self.__get_item('quantity') - - @quantity.setter - def quantity(self, value): - """Sets the quantity of this Order. # noqa: E501 - """ - return self.__set_item('quantity', value) - - @property - def ship_date(self): - """Gets the ship_date of this Order. # noqa: E501 - - Returns: - (datetime): The ship_date of this Order. # noqa: E501 - """ - return self.__get_item('ship_date') - - @ship_date.setter - def ship_date(self, value): - """Sets the ship_date of this Order. # noqa: E501 - """ - return self.__set_item('ship_date', value) - - @property - def status(self): - """Gets the status of this Order. # noqa: E501 - Order Status # noqa: E501 - - Returns: - (str): The status of this Order. # noqa: E501 - """ - return self.__get_item('status') - - @status.setter - def status(self, value): - """Sets the status of this Order. # noqa: E501 - Order Status # noqa: E501 - """ - return self.__set_item('status', value) - - @property - def complete(self): - """Gets the complete of this Order. # noqa: E501 - - Returns: - (bool): The complete of this Order. # noqa: E501 - """ - return self.__get_item('complete') - - @complete.setter - def complete(self, value): - """Sets the complete of this Order. # noqa: E501 - """ - return self.__set_item('complete', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Order): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py index 61bc5054575..6ad00966eae 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py @@ -10,33 +10,28 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.outer_number import OuterNumber +try: + from petstore_api.models import outer_number +except ImportError: + outer_number = sys.modules['petstore_api.models.outer_number'] class OuterComposite(ModelNormal): @@ -68,14 +63,8 @@ class OuterComposite(ModelNormal): allowed_values = { } - attribute_map = { - 'my_number': 'my_number', # noqa: E501 - 'my_string': 'my_string', # noqa: E501 - 'my_boolean': 'my_boolean' # noqa: E501 - } - openapi_types = { - 'my_number': (OuterNumber,), # noqa: E501 + 'my_number': (outer_number.OuterNumber,), # noqa: E501 'my_string': (str,), # noqa: E501 'my_boolean': (bool,), # noqa: E501 } @@ -85,10 +74,30 @@ class OuterComposite(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'my_number': 'my_number', # noqa: E501 + 'my_string': 'my_string', # noqa: E501 + 'my_boolean': 'my_boolean', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """OuterComposite - a model defined in OpenAPI + """outer_composite.OuterComposite - a model defined in OpenAPI Keyword Args: @@ -105,10 +114,11 @@ class OuterComposite(ModelNormal): deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. - my_number (OuterNumber): [optional] # noqa: E501 + my_number (outer_number.OuterNumber): [optional] # noqa: E501 my_string (str): [optional] # noqa: E501 my_boolean (bool): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -116,156 +126,4 @@ class OuterComposite(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def my_number(self): - """Gets the my_number of this OuterComposite. # noqa: E501 - - Returns: - (OuterNumber): The my_number of this OuterComposite. # noqa: E501 - """ - return self.__get_item('my_number') - - @my_number.setter - def my_number(self, value): - """Sets the my_number of this OuterComposite. # noqa: E501 - """ - return self.__set_item('my_number', value) - - @property - def my_string(self): - """Gets the my_string of this OuterComposite. # noqa: E501 - - Returns: - (str): The my_string of this OuterComposite. # noqa: E501 - """ - return self.__get_item('my_string') - - @my_string.setter - def my_string(self, value): - """Sets the my_string of this OuterComposite. # noqa: E501 - """ - return self.__set_item('my_string', value) - - @property - def my_boolean(self): - """Gets the my_boolean of this OuterComposite. # noqa: E501 - - Returns: - (bool): The my_boolean of this OuterComposite. # noqa: E501 - """ - return self.__get_item('my_boolean') - - @my_boolean.setter - def my_boolean(self, value): - """Sets the my_boolean of this OuterComposite. # noqa: E501 - """ - return self.__set_item('my_boolean', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OuterComposite): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py index e10dfc65118..39b104f6427 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -77,10 +69,24 @@ class OuterEnum(ModelSimple): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, value, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """OuterEnum - a model defined in OpenAPI + """outer_enum.OuterEnum - a model defined in OpenAPI Args: value (str): @@ -100,127 +106,13 @@ class OuterEnum(ModelSimple): If passed, type conversion is attempted If omitted no type conversion is done. """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('value', value) + self.value = value for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def value(self): - """Gets the value of this OuterEnum. # noqa: E501 - - Returns: - (str): The value of this OuterEnum. # noqa: E501 - """ - return self.__get_item('value') - - @value.setter - def value(self, value): - """Sets the value of this OuterEnum. # noqa: E501 - """ - return self.__set_item('value', value) - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OuterEnum): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py index ca2be68a97e..362a3cf1fc5 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -76,10 +68,24 @@ class OuterNumber(ModelSimple): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, value, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """OuterNumber - a model defined in OpenAPI + """outer_number.OuterNumber - a model defined in OpenAPI Args: value (float): @@ -99,127 +105,13 @@ class OuterNumber(ModelSimple): If passed, type conversion is attempted If omitted no type conversion is done. """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('value', value) + self.value = value for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def value(self): - """Gets the value of this OuterNumber. # noqa: E501 - - Returns: - (float): The value of this OuterNumber. # noqa: E501 - """ - return self.__get_item('value') - - @value.setter - def value(self, value): - """Sets the value of this OuterNumber. # noqa: E501 - """ - return self.__set_item('value', value) - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OuterNumber): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent.py b/samples/client/petstore/python-experimental/petstore_api/models/parent.py new file mode 100644 index 00000000000..d07ca49d4de --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent.py @@ -0,0 +1,164 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import grandparent +except ImportError: + grandparent = sys.modules['petstore_api.models.grandparent'] +try: + from petstore_api.models import parent_all_of +except ImportError: + parent_all_of = sys.modules['petstore_api.models.parent_all_of'] + + +class Parent(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'radio_waves': (bool,), # noqa: E501 + 'tele_vision': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + 'tele_vision': 'teleVision', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """parent.Parent - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + grandparent.Grandparent, + parent_all_of.ParentAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py new file mode 100644 index 00000000000..0cfcbda855d --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class ParentAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'tele_vision': (bool,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'tele_vision': 'teleVision', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """parent_all_of.ParentAllOf - a model defined in OpenAPI + + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + tele_vision (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py b/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py new file mode 100644 index 00000000000..59b890e8914 --- /dev/null +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py @@ -0,0 +1,190 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import child_cat +except ImportError: + child_cat = sys.modules['petstore_api.models.child_cat'] +try: + from petstore_api.models import child_dog +except ImportError: + child_dog = sys.modules['petstore_api.models.child_dog'] +try: + from petstore_api.models import child_lizard +except ImportError: + child_lizard = sys.modules['petstore_api.models.child_lizard'] +try: + from petstore_api.models import grandparent_animal +except ImportError: + grandparent_animal = sys.modules['petstore_api.models.grandparent_animal'] + + +class ParentPet(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + openapi_types (dict): The key is attribute name + and the value is attribute type. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + openapi_types = { + 'pet_type': (str,), # noqa: E501 + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def discriminator(): + return { + 'pet_type': { + 'ChildCat': child_cat.ChildCat, + 'ChildDog': child_dog.ChildDog, + 'ChildLizard': child_lizard.ChildLizard, + }, + } + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """parent_pet.ParentPet - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'pet_type': pet_type, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.pet_type = pet_type + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + grandparent_animal.GrandparentAnimal, + ], + 'oneOf': [ + ], + } + + @classmethod + def get_discriminator_class(cls, from_server, data): + """Returns the child class specified by the discriminator""" + discriminator = cls.discriminator() + discr_propertyname_py = list(discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if from_server: + class_name = data[discr_propertyname_js] + else: + class_name = data[discr_propertyname_py] + class_name_to_discr_class = discriminator[discr_propertyname_py] + return class_name_to_discr_class.get(class_name) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/pet.py b/samples/client/petstore/python-experimental/petstore_api/models/pet.py index 3abfdfba760..081be0210e6 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/pet.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/pet.py @@ -10,34 +10,32 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) -from petstore_api.models.category import Category -from petstore_api.models.tag import Tag +try: + from petstore_api.models import category +except ImportError: + category = sys.modules['petstore_api.models.category'] +try: + from petstore_api.models import tag +except ImportError: + tag = sys.modules['petstore_api.models.tag'] class Pet(ModelNormal): @@ -74,21 +72,12 @@ class Pet(ModelNormal): }, } - attribute_map = { - 'id': 'id', # noqa: E501 - 'category': 'category', # noqa: E501 - 'name': 'name', # noqa: E501 - 'photo_urls': 'photoUrls', # noqa: E501 - 'tags': 'tags', # noqa: E501 - 'status': 'status' # noqa: E501 - } - openapi_types = { - 'id': (int,), # noqa: E501 - 'category': (Category,), # noqa: E501 'name': (str,), # noqa: E501 'photo_urls': ([str],), # noqa: E501 - 'tags': ([Tag],), # noqa: E501 + 'id': (int,), # noqa: E501 + 'category': (category.Category,), # noqa: E501 + 'tags': ([tag.Tag],), # noqa: E501 'status': (str,), # noqa: E501 } @@ -97,10 +86,33 @@ class Pet(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'name': 'name', # noqa: E501 + 'photo_urls': 'photoUrls', # noqa: E501 + 'id': 'id', # noqa: E501 + 'category': 'category', # noqa: E501 + 'tags': 'tags', # noqa: E501 + 'status': 'status', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, name, photo_urls, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Pet - a model defined in OpenAPI + """pet.Pet - a model defined in OpenAPI Args: name (str): @@ -121,216 +133,18 @@ class Pet(ModelNormal): If passed, type conversion is attempted If omitted no type conversion is done. id (int): [optional] # noqa: E501 - category (Category): [optional] # noqa: E501 - tags ([Tag]): [optional] # noqa: E501 + category (category.Category): [optional] # noqa: E501 + tags ([tag.Tag]): [optional] # noqa: E501 status (str): pet status in the store. [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('name', name) - self.__set_item('photo_urls', photo_urls) + self.name = name + self.photo_urls = photo_urls for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def id(self): - """Gets the id of this Pet. # noqa: E501 - - Returns: - (int): The id of this Pet. # noqa: E501 - """ - return self.__get_item('id') - - @id.setter - def id(self, value): - """Sets the id of this Pet. # noqa: E501 - """ - return self.__set_item('id', value) - - @property - def category(self): - """Gets the category of this Pet. # noqa: E501 - - Returns: - (Category): The category of this Pet. # noqa: E501 - """ - return self.__get_item('category') - - @category.setter - def category(self, value): - """Sets the category of this Pet. # noqa: E501 - """ - return self.__set_item('category', value) - - @property - def name(self): - """Gets the name of this Pet. # noqa: E501 - - Returns: - (str): The name of this Pet. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this Pet. # noqa: E501 - """ - return self.__set_item('name', value) - - @property - def photo_urls(self): - """Gets the photo_urls of this Pet. # noqa: E501 - - Returns: - ([str]): The photo_urls of this Pet. # noqa: E501 - """ - return self.__get_item('photo_urls') - - @photo_urls.setter - def photo_urls(self, value): - """Sets the photo_urls of this Pet. # noqa: E501 - """ - return self.__set_item('photo_urls', value) - - @property - def tags(self): - """Gets the tags of this Pet. # noqa: E501 - - Returns: - ([Tag]): The tags of this Pet. # noqa: E501 - """ - return self.__get_item('tags') - - @tags.setter - def tags(self, value): - """Sets the tags of this Pet. # noqa: E501 - """ - return self.__set_item('tags', value) - - @property - def status(self): - """Gets the status of this Pet. # noqa: E501 - pet status in the store # noqa: E501 - - Returns: - (str): The status of this Pet. # noqa: E501 - """ - return self.__get_item('status') - - @status.setter - def status(self, value): - """Sets the status of this Pet. # noqa: E501 - pet status in the store # noqa: E501 - """ - return self.__set_item('status', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Pet): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py b/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py index 848fbccfa91..71ca2052912 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,11 +59,6 @@ class ReadOnlyFirst(ModelNormal): allowed_values = { } - attribute_map = { - 'bar': 'bar', # noqa: E501 - 'baz': 'baz' # noqa: E501 - } - openapi_types = { 'bar': (str,), # noqa: E501 'baz': (str,), # noqa: E501 @@ -82,10 +69,29 @@ class ReadOnlyFirst(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'baz': 'baz', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """ReadOnlyFirst - a model defined in OpenAPI + """read_only_first.ReadOnlyFirst - a model defined in OpenAPI Keyword Args: @@ -105,6 +111,7 @@ class ReadOnlyFirst(ModelNormal): bar (str): [optional] # noqa: E501 baz (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -112,141 +119,4 @@ class ReadOnlyFirst(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def bar(self): - """Gets the bar of this ReadOnlyFirst. # noqa: E501 - - Returns: - (str): The bar of this ReadOnlyFirst. # noqa: E501 - """ - return self.__get_item('bar') - - @bar.setter - def bar(self, value): - """Sets the bar of this ReadOnlyFirst. # noqa: E501 - """ - return self.__set_item('bar', value) - - @property - def baz(self): - """Gets the baz of this ReadOnlyFirst. # noqa: E501 - - Returns: - (str): The baz of this ReadOnlyFirst. # noqa: E501 - """ - return self.__get_item('baz') - - @baz.setter - def baz(self, value): - """Sets the baz of this ReadOnlyFirst. # noqa: E501 - """ - return self.__set_item('baz', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ReadOnlyFirst): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py b/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py index 83810bdb894..574c3817d78 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,10 +59,6 @@ class SpecialModelName(ModelNormal): allowed_values = { } - attribute_map = { - 'special_property_name': '$special[property.name]' # noqa: E501 - } - openapi_types = { 'special_property_name': (int,), # noqa: E501 } @@ -80,10 +68,28 @@ class SpecialModelName(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'special_property_name': '$special[property.name]', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """SpecialModelName - a model defined in OpenAPI + """special_model_name.SpecialModelName - a model defined in OpenAPI Keyword Args: @@ -102,6 +108,7 @@ class SpecialModelName(ModelNormal): If omitted no type conversion is done. special_property_name (int): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -109,126 +116,4 @@ class SpecialModelName(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def special_property_name(self): - """Gets the special_property_name of this SpecialModelName. # noqa: E501 - - Returns: - (int): The special_property_name of this SpecialModelName. # noqa: E501 - """ - return self.__get_item('special_property_name') - - @special_property_name.setter - def special_property_name(self, value): - """Sets the special_property_name of this SpecialModelName. # noqa: E501 - """ - return self.__set_item('special_property_name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, SpecialModelName): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py b/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py index 1d10f9a8d7e..19b3cd131c0 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,9 +59,6 @@ class StringBooleanMap(ModelNormal): allowed_values = { } - attribute_map = { - } - openapi_types = { } @@ -78,10 +67,27 @@ class StringBooleanMap(ModelNormal): additional_properties_type = (bool,) # noqa: E501 - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """StringBooleanMap - a model defined in OpenAPI + """string_boolean_map.StringBooleanMap - a model defined in OpenAPI Keyword Args: @@ -99,6 +105,7 @@ class StringBooleanMap(ModelNormal): If passed, type conversion is attempted If omitted no type conversion is done. """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -106,111 +113,4 @@ class StringBooleanMap(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, StringBooleanMap): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/tag.py b/samples/client/petstore/python-experimental/petstore_api/models/tag.py index 4e1fd5ef077..590b234d4d4 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/tag.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/tag.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,14 +59,10 @@ class Tag(ModelNormal): allowed_values = { } - attribute_map = { - 'id': 'id', # noqa: E501 - 'name': 'name' # noqa: E501 - } - openapi_types = { 'id': (int,), # noqa: E501 'name': (str,), # noqa: E501 + 'full_name': (str,), # noqa: E501 } validations = { @@ -82,10 +70,30 @@ class Tag(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'id': 'id', # noqa: E501 + 'name': 'name', # noqa: E501 + 'full_name': 'fullName', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """Tag - a model defined in OpenAPI + """tag.Tag - a model defined in OpenAPI Keyword Args: @@ -104,7 +112,9 @@ class Tag(ModelNormal): If omitted no type conversion is done. id (int): [optional] # noqa: E501 name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -112,141 +122,4 @@ class Tag(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def id(self): - """Gets the id of this Tag. # noqa: E501 - - Returns: - (int): The id of this Tag. # noqa: E501 - """ - return self.__get_item('id') - - @id.setter - def id(self, value): - """Sets the id of this Tag. # noqa: E501 - """ - return self.__set_item('id', value) - - @property - def name(self): - """Gets the name of this Tag. # noqa: E501 - - Returns: - (str): The name of this Tag. # noqa: E501 - """ - return self.__get_item('name') - - @name.setter - def name(self, value): - """Sets the name of this Tag. # noqa: E501 - """ - return self.__set_item('name', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Tag): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py index 26f1d904452..71b4719f5dd 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,24 +59,14 @@ class TypeHolderDefault(ModelNormal): allowed_values = { } - attribute_map = { - 'string_item': 'string_item', # noqa: E501 - 'number_item': 'number_item', # noqa: E501 - 'integer_item': 'integer_item', # noqa: E501 - 'bool_item': 'bool_item', # noqa: E501 - 'date_item': 'date_item', # noqa: E501 - 'datetime_item': 'datetime_item', # noqa: E501 - 'array_item': 'array_item' # noqa: E501 - } - openapi_types = { 'string_item': (str,), # noqa: E501 'number_item': (float,), # noqa: E501 'integer_item': (int,), # noqa: E501 'bool_item': (bool,), # noqa: E501 + 'array_item': ([int],), # noqa: E501 'date_item': (date,), # noqa: E501 'datetime_item': (datetime,), # noqa: E501 - 'array_item': ([int],), # noqa: E501 } validations = { @@ -92,10 +74,34 @@ class TypeHolderDefault(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'string_item': 'string_item', # noqa: E501 + 'number_item': 'number_item', # noqa: E501 + 'integer_item': 'integer_item', # noqa: E501 + 'bool_item': 'bool_item', # noqa: E501 + 'array_item': 'array_item', # noqa: E501 + 'date_item': 'date_item', # noqa: E501 + 'datetime_item': 'datetime_item', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, array_item, string_item='what', number_item=1.234, integer_item=-2, bool_item=True, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """TypeHolderDefault - a model defined in OpenAPI + """type_holder_default.TypeHolderDefault - a model defined in OpenAPI Args: array_item ([int]): @@ -121,228 +127,17 @@ class TypeHolderDefault(ModelNormal): date_item (date): [optional] # noqa: E501 datetime_item (datetime): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('string_item', string_item) - self.__set_item('number_item', number_item) - self.__set_item('integer_item', integer_item) - self.__set_item('bool_item', bool_item) - self.__set_item('array_item', array_item) + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def string_item(self): - """Gets the string_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (str): The string_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('string_item') - - @string_item.setter - def string_item(self, value): - """Sets the string_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('string_item', value) - - @property - def number_item(self): - """Gets the number_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (float): The number_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('number_item') - - @number_item.setter - def number_item(self, value): - """Sets the number_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('number_item', value) - - @property - def integer_item(self): - """Gets the integer_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (int): The integer_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('integer_item') - - @integer_item.setter - def integer_item(self, value): - """Sets the integer_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('integer_item', value) - - @property - def bool_item(self): - """Gets the bool_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (bool): The bool_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('bool_item') - - @bool_item.setter - def bool_item(self, value): - """Sets the bool_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('bool_item', value) - - @property - def date_item(self): - """Gets the date_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (date): The date_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('date_item') - - @date_item.setter - def date_item(self, value): - """Sets the date_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('date_item', value) - - @property - def datetime_item(self): - """Gets the datetime_item of this TypeHolderDefault. # noqa: E501 - - Returns: - (datetime): The datetime_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('datetime_item') - - @datetime_item.setter - def datetime_item(self, value): - """Sets the datetime_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('datetime_item', value) - - @property - def array_item(self): - """Gets the array_item of this TypeHolderDefault. # noqa: E501 - - Returns: - ([int]): The array_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__get_item('array_item') - - @array_item.setter - def array_item(self, value): - """Sets the array_item of this TypeHolderDefault. # noqa: E501 - """ - return self.__set_item('array_item', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TypeHolderDefault): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py index b4fb4770d1e..96b8551dd1a 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -76,14 +68,6 @@ class TypeHolderExample(ModelNormal): }, } - attribute_map = { - 'string_item': 'string_item', # noqa: E501 - 'number_item': 'number_item', # noqa: E501 - 'integer_item': 'integer_item', # noqa: E501 - 'bool_item': 'bool_item', # noqa: E501 - 'array_item': 'array_item' # noqa: E501 - } - openapi_types = { 'string_item': (str,), # noqa: E501 'number_item': (float,), # noqa: E501 @@ -97,10 +81,32 @@ class TypeHolderExample(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'string_item': 'string_item', # noqa: E501 + 'number_item': 'number_item', # noqa: E501 + 'integer_item': 'integer_item', # noqa: E501 + 'bool_item': 'bool_item', # noqa: E501 + 'array_item': 'array_item', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, bool_item, array_item, string_item='what', number_item=1.234, integer_item=-2, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """TypeHolderExample - a model defined in OpenAPI + """type_holder_example.TypeHolderExample - a model defined in OpenAPI Args: bool_item (bool): @@ -124,198 +130,17 @@ class TypeHolderExample(ModelNormal): If passed, type conversion is attempted If omitted no type conversion is done. """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server self._path_to_item = _path_to_item self._configuration = _configuration - self.__set_item('string_item', string_item) - self.__set_item('number_item', number_item) - self.__set_item('integer_item', integer_item) - self.__set_item('bool_item', bool_item) - self.__set_item('array_item', array_item) + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def string_item(self): - """Gets the string_item of this TypeHolderExample. # noqa: E501 - - Returns: - (str): The string_item of this TypeHolderExample. # noqa: E501 - """ - return self.__get_item('string_item') - - @string_item.setter - def string_item(self, value): - """Sets the string_item of this TypeHolderExample. # noqa: E501 - """ - return self.__set_item('string_item', value) - - @property - def number_item(self): - """Gets the number_item of this TypeHolderExample. # noqa: E501 - - Returns: - (float): The number_item of this TypeHolderExample. # noqa: E501 - """ - return self.__get_item('number_item') - - @number_item.setter - def number_item(self, value): - """Sets the number_item of this TypeHolderExample. # noqa: E501 - """ - return self.__set_item('number_item', value) - - @property - def integer_item(self): - """Gets the integer_item of this TypeHolderExample. # noqa: E501 - - Returns: - (int): The integer_item of this TypeHolderExample. # noqa: E501 - """ - return self.__get_item('integer_item') - - @integer_item.setter - def integer_item(self, value): - """Sets the integer_item of this TypeHolderExample. # noqa: E501 - """ - return self.__set_item('integer_item', value) - - @property - def bool_item(self): - """Gets the bool_item of this TypeHolderExample. # noqa: E501 - - Returns: - (bool): The bool_item of this TypeHolderExample. # noqa: E501 - """ - return self.__get_item('bool_item') - - @bool_item.setter - def bool_item(self, value): - """Sets the bool_item of this TypeHolderExample. # noqa: E501 - """ - return self.__set_item('bool_item', value) - - @property - def array_item(self): - """Gets the array_item of this TypeHolderExample. # noqa: E501 - - Returns: - ([int]): The array_item of this TypeHolderExample. # noqa: E501 - """ - return self.__get_item('array_item') - - @array_item.setter - def array_item(self, value): - """Sets the array_item of this TypeHolderExample. # noqa: E501 - """ - return self.__set_item('array_item', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TypeHolderExample): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/user.py b/samples/client/petstore/python-experimental/petstore_api/models/user.py index 6d4d4539a84..03b3ef6a5e6 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/user.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/user.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,17 +59,6 @@ class User(ModelNormal): allowed_values = { } - attribute_map = { - 'id': 'id', # noqa: E501 - 'username': 'username', # noqa: E501 - 'first_name': 'firstName', # noqa: E501 - 'last_name': 'lastName', # noqa: E501 - 'email': 'email', # noqa: E501 - 'password': 'password', # noqa: E501 - 'phone': 'phone', # noqa: E501 - 'user_status': 'userStatus' # noqa: E501 - } - openapi_types = { 'id': (int,), # noqa: E501 'username': (str,), # noqa: E501 @@ -94,10 +75,35 @@ class User(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'id': 'id', # noqa: E501 + 'username': 'username', # noqa: E501 + 'first_name': 'firstName', # noqa: E501 + 'last_name': 'lastName', # noqa: E501 + 'email': 'email', # noqa: E501 + 'password': 'password', # noqa: E501 + 'phone': 'phone', # noqa: E501 + 'user_status': 'userStatus', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """User - a model defined in OpenAPI + """user.User - a model defined in OpenAPI Keyword Args: @@ -123,6 +129,7 @@ class User(ModelNormal): phone (str): [optional] # noqa: E501 user_status (int): User Status. [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -130,233 +137,4 @@ class User(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def id(self): - """Gets the id of this User. # noqa: E501 - - Returns: - (int): The id of this User. # noqa: E501 - """ - return self.__get_item('id') - - @id.setter - def id(self, value): - """Sets the id of this User. # noqa: E501 - """ - return self.__set_item('id', value) - - @property - def username(self): - """Gets the username of this User. # noqa: E501 - - Returns: - (str): The username of this User. # noqa: E501 - """ - return self.__get_item('username') - - @username.setter - def username(self, value): - """Sets the username of this User. # noqa: E501 - """ - return self.__set_item('username', value) - - @property - def first_name(self): - """Gets the first_name of this User. # noqa: E501 - - Returns: - (str): The first_name of this User. # noqa: E501 - """ - return self.__get_item('first_name') - - @first_name.setter - def first_name(self, value): - """Sets the first_name of this User. # noqa: E501 - """ - return self.__set_item('first_name', value) - - @property - def last_name(self): - """Gets the last_name of this User. # noqa: E501 - - Returns: - (str): The last_name of this User. # noqa: E501 - """ - return self.__get_item('last_name') - - @last_name.setter - def last_name(self, value): - """Sets the last_name of this User. # noqa: E501 - """ - return self.__set_item('last_name', value) - - @property - def email(self): - """Gets the email of this User. # noqa: E501 - - Returns: - (str): The email of this User. # noqa: E501 - """ - return self.__get_item('email') - - @email.setter - def email(self, value): - """Sets the email of this User. # noqa: E501 - """ - return self.__set_item('email', value) - - @property - def password(self): - """Gets the password of this User. # noqa: E501 - - Returns: - (str): The password of this User. # noqa: E501 - """ - return self.__get_item('password') - - @password.setter - def password(self, value): - """Sets the password of this User. # noqa: E501 - """ - return self.__set_item('password', value) - - @property - def phone(self): - """Gets the phone of this User. # noqa: E501 - - Returns: - (str): The phone of this User. # noqa: E501 - """ - return self.__get_item('phone') - - @phone.setter - def phone(self, value): - """Sets the phone of this User. # noqa: E501 - """ - return self.__set_item('phone', value) - - @property - def user_status(self): - """Gets the user_status of this User. # noqa: E501 - User Status # noqa: E501 - - Returns: - (int): The user_status of this User. # noqa: E501 - """ - return self.__get_item('user_status') - - @user_status.setter - def user_status(self, value): - """Sets the user_status of this User. # noqa: E501 - User Status # noqa: E501 - """ - return self.__set_item('user_status', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, User): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py b/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py index f7ded778c29..a38afa9cfbe 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py @@ -10,31 +10,23 @@ """ -import pprint # noqa: F401 +from __future__ import absolute_import import re # noqa: F401 +import sys # noqa: F401 import six # noqa: F401 -from petstore_api.exceptions import ( # noqa: F401 - ApiKeyError, - ApiTypeError, - ApiValueError, -) from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, ModelNormal, ModelSimple, - check_allowed_values, - check_validations, date, datetime, file_type, - get_simple_class, int, - model_to_dict, none_type, str, - type_error_message, - validate_and_convert_types + validate_get_composed_info, ) @@ -67,38 +59,6 @@ class XmlItem(ModelNormal): allowed_values = { } - attribute_map = { - 'attribute_string': 'attribute_string', # noqa: E501 - 'attribute_number': 'attribute_number', # noqa: E501 - 'attribute_integer': 'attribute_integer', # noqa: E501 - 'attribute_boolean': 'attribute_boolean', # noqa: E501 - 'wrapped_array': 'wrapped_array', # noqa: E501 - 'name_string': 'name_string', # noqa: E501 - 'name_number': 'name_number', # noqa: E501 - 'name_integer': 'name_integer', # noqa: E501 - 'name_boolean': 'name_boolean', # noqa: E501 - 'name_array': 'name_array', # noqa: E501 - 'name_wrapped_array': 'name_wrapped_array', # noqa: E501 - 'prefix_string': 'prefix_string', # noqa: E501 - 'prefix_number': 'prefix_number', # noqa: E501 - 'prefix_integer': 'prefix_integer', # noqa: E501 - 'prefix_boolean': 'prefix_boolean', # noqa: E501 - 'prefix_array': 'prefix_array', # noqa: E501 - 'prefix_wrapped_array': 'prefix_wrapped_array', # noqa: E501 - 'namespace_string': 'namespace_string', # noqa: E501 - 'namespace_number': 'namespace_number', # noqa: E501 - 'namespace_integer': 'namespace_integer', # noqa: E501 - 'namespace_boolean': 'namespace_boolean', # noqa: E501 - 'namespace_array': 'namespace_array', # noqa: E501 - 'namespace_wrapped_array': 'namespace_wrapped_array', # noqa: E501 - 'prefix_ns_string': 'prefix_ns_string', # noqa: E501 - 'prefix_ns_number': 'prefix_ns_number', # noqa: E501 - 'prefix_ns_integer': 'prefix_ns_integer', # noqa: E501 - 'prefix_ns_boolean': 'prefix_ns_boolean', # noqa: E501 - 'prefix_ns_array': 'prefix_ns_array', # noqa: E501 - 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array' # noqa: E501 - } - openapi_types = { 'attribute_string': (str,), # noqa: E501 'attribute_number': (float,), # noqa: E501 @@ -136,10 +96,56 @@ class XmlItem(ModelNormal): additional_properties_type = None - discriminator = None + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'attribute_string': 'attribute_string', # noqa: E501 + 'attribute_number': 'attribute_number', # noqa: E501 + 'attribute_integer': 'attribute_integer', # noqa: E501 + 'attribute_boolean': 'attribute_boolean', # noqa: E501 + 'wrapped_array': 'wrapped_array', # noqa: E501 + 'name_string': 'name_string', # noqa: E501 + 'name_number': 'name_number', # noqa: E501 + 'name_integer': 'name_integer', # noqa: E501 + 'name_boolean': 'name_boolean', # noqa: E501 + 'name_array': 'name_array', # noqa: E501 + 'name_wrapped_array': 'name_wrapped_array', # noqa: E501 + 'prefix_string': 'prefix_string', # noqa: E501 + 'prefix_number': 'prefix_number', # noqa: E501 + 'prefix_integer': 'prefix_integer', # noqa: E501 + 'prefix_boolean': 'prefix_boolean', # noqa: E501 + 'prefix_array': 'prefix_array', # noqa: E501 + 'prefix_wrapped_array': 'prefix_wrapped_array', # noqa: E501 + 'namespace_string': 'namespace_string', # noqa: E501 + 'namespace_number': 'namespace_number', # noqa: E501 + 'namespace_integer': 'namespace_integer', # noqa: E501 + 'namespace_boolean': 'namespace_boolean', # noqa: E501 + 'namespace_array': 'namespace_array', # noqa: E501 + 'namespace_wrapped_array': 'namespace_wrapped_array', # noqa: E501 + 'prefix_ns_string': 'prefix_ns_string', # noqa: E501 + 'prefix_ns_number': 'prefix_ns_number', # noqa: E501 + 'prefix_ns_integer': 'prefix_ns_integer', # noqa: E501 + 'prefix_ns_boolean': 'prefix_ns_boolean', # noqa: E501 + 'prefix_ns_array': 'prefix_ns_array', # noqa: E501 + 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 - """XmlItem - a model defined in OpenAPI + """xml_item.XmlItem - a model defined in OpenAPI Keyword Args: @@ -186,6 +192,7 @@ class XmlItem(ModelNormal): prefix_ns_array ([int]): [optional] # noqa: E501 prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 """ + self._data_store = {} self._check_type = _check_type self._from_server = _from_server @@ -193,546 +200,4 @@ class XmlItem(ModelNormal): self._configuration = _configuration for var_name, var_value in six.iteritems(kwargs): - self.__set_item(var_name, var_value) - - def __set_item(self, name, value): - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._from_server, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value - ) - self._data_store[name] = value - - def __get_item(self, name): - if name in self._data_store: - return self._data_store[name] - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - [name] - ) - - def __setitem__(self, name, value): - """this allows us to set values with instance[field_name] = val""" - self.__set_item(name, value) - - def __getitem__(self, name): - """this allows us to get a value with val = instance[field_name]""" - return self.__get_item(name) - - @property - def attribute_string(self): - """Gets the attribute_string of this XmlItem. # noqa: E501 - - Returns: - (str): The attribute_string of this XmlItem. # noqa: E501 - """ - return self.__get_item('attribute_string') - - @attribute_string.setter - def attribute_string(self, value): - """Sets the attribute_string of this XmlItem. # noqa: E501 - """ - return self.__set_item('attribute_string', value) - - @property - def attribute_number(self): - """Gets the attribute_number of this XmlItem. # noqa: E501 - - Returns: - (float): The attribute_number of this XmlItem. # noqa: E501 - """ - return self.__get_item('attribute_number') - - @attribute_number.setter - def attribute_number(self, value): - """Sets the attribute_number of this XmlItem. # noqa: E501 - """ - return self.__set_item('attribute_number', value) - - @property - def attribute_integer(self): - """Gets the attribute_integer of this XmlItem. # noqa: E501 - - Returns: - (int): The attribute_integer of this XmlItem. # noqa: E501 - """ - return self.__get_item('attribute_integer') - - @attribute_integer.setter - def attribute_integer(self, value): - """Sets the attribute_integer of this XmlItem. # noqa: E501 - """ - return self.__set_item('attribute_integer', value) - - @property - def attribute_boolean(self): - """Gets the attribute_boolean of this XmlItem. # noqa: E501 - - Returns: - (bool): The attribute_boolean of this XmlItem. # noqa: E501 - """ - return self.__get_item('attribute_boolean') - - @attribute_boolean.setter - def attribute_boolean(self, value): - """Sets the attribute_boolean of this XmlItem. # noqa: E501 - """ - return self.__set_item('attribute_boolean', value) - - @property - def wrapped_array(self): - """Gets the wrapped_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('wrapped_array') - - @wrapped_array.setter - def wrapped_array(self, value): - """Sets the wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('wrapped_array', value) - - @property - def name_string(self): - """Gets the name_string of this XmlItem. # noqa: E501 - - Returns: - (str): The name_string of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_string') - - @name_string.setter - def name_string(self, value): - """Sets the name_string of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_string', value) - - @property - def name_number(self): - """Gets the name_number of this XmlItem. # noqa: E501 - - Returns: - (float): The name_number of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_number') - - @name_number.setter - def name_number(self, value): - """Sets the name_number of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_number', value) - - @property - def name_integer(self): - """Gets the name_integer of this XmlItem. # noqa: E501 - - Returns: - (int): The name_integer of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_integer') - - @name_integer.setter - def name_integer(self, value): - """Sets the name_integer of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_integer', value) - - @property - def name_boolean(self): - """Gets the name_boolean of this XmlItem. # noqa: E501 - - Returns: - (bool): The name_boolean of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_boolean') - - @name_boolean.setter - def name_boolean(self, value): - """Sets the name_boolean of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_boolean', value) - - @property - def name_array(self): - """Gets the name_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The name_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_array') - - @name_array.setter - def name_array(self, value): - """Sets the name_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_array', value) - - @property - def name_wrapped_array(self): - """Gets the name_wrapped_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The name_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('name_wrapped_array') - - @name_wrapped_array.setter - def name_wrapped_array(self, value): - """Sets the name_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('name_wrapped_array', value) - - @property - def prefix_string(self): - """Gets the prefix_string of this XmlItem. # noqa: E501 - - Returns: - (str): The prefix_string of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_string') - - @prefix_string.setter - def prefix_string(self, value): - """Sets the prefix_string of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_string', value) - - @property - def prefix_number(self): - """Gets the prefix_number of this XmlItem. # noqa: E501 - - Returns: - (float): The prefix_number of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_number') - - @prefix_number.setter - def prefix_number(self, value): - """Sets the prefix_number of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_number', value) - - @property - def prefix_integer(self): - """Gets the prefix_integer of this XmlItem. # noqa: E501 - - Returns: - (int): The prefix_integer of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_integer') - - @prefix_integer.setter - def prefix_integer(self, value): - """Sets the prefix_integer of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_integer', value) - - @property - def prefix_boolean(self): - """Gets the prefix_boolean of this XmlItem. # noqa: E501 - - Returns: - (bool): The prefix_boolean of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_boolean') - - @prefix_boolean.setter - def prefix_boolean(self, value): - """Sets the prefix_boolean of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_boolean', value) - - @property - def prefix_array(self): - """Gets the prefix_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The prefix_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_array') - - @prefix_array.setter - def prefix_array(self, value): - """Sets the prefix_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_array', value) - - @property - def prefix_wrapped_array(self): - """Gets the prefix_wrapped_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The prefix_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_wrapped_array') - - @prefix_wrapped_array.setter - def prefix_wrapped_array(self, value): - """Sets the prefix_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_wrapped_array', value) - - @property - def namespace_string(self): - """Gets the namespace_string of this XmlItem. # noqa: E501 - - Returns: - (str): The namespace_string of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_string') - - @namespace_string.setter - def namespace_string(self, value): - """Sets the namespace_string of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_string', value) - - @property - def namespace_number(self): - """Gets the namespace_number of this XmlItem. # noqa: E501 - - Returns: - (float): The namespace_number of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_number') - - @namespace_number.setter - def namespace_number(self, value): - """Sets the namespace_number of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_number', value) - - @property - def namespace_integer(self): - """Gets the namespace_integer of this XmlItem. # noqa: E501 - - Returns: - (int): The namespace_integer of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_integer') - - @namespace_integer.setter - def namespace_integer(self, value): - """Sets the namespace_integer of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_integer', value) - - @property - def namespace_boolean(self): - """Gets the namespace_boolean of this XmlItem. # noqa: E501 - - Returns: - (bool): The namespace_boolean of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_boolean') - - @namespace_boolean.setter - def namespace_boolean(self, value): - """Sets the namespace_boolean of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_boolean', value) - - @property - def namespace_array(self): - """Gets the namespace_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The namespace_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_array') - - @namespace_array.setter - def namespace_array(self, value): - """Sets the namespace_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_array', value) - - @property - def namespace_wrapped_array(self): - """Gets the namespace_wrapped_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The namespace_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('namespace_wrapped_array') - - @namespace_wrapped_array.setter - def namespace_wrapped_array(self, value): - """Sets the namespace_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('namespace_wrapped_array', value) - - @property - def prefix_ns_string(self): - """Gets the prefix_ns_string of this XmlItem. # noqa: E501 - - Returns: - (str): The prefix_ns_string of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_string') - - @prefix_ns_string.setter - def prefix_ns_string(self, value): - """Sets the prefix_ns_string of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_string', value) - - @property - def prefix_ns_number(self): - """Gets the prefix_ns_number of this XmlItem. # noqa: E501 - - Returns: - (float): The prefix_ns_number of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_number') - - @prefix_ns_number.setter - def prefix_ns_number(self, value): - """Sets the prefix_ns_number of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_number', value) - - @property - def prefix_ns_integer(self): - """Gets the prefix_ns_integer of this XmlItem. # noqa: E501 - - Returns: - (int): The prefix_ns_integer of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_integer') - - @prefix_ns_integer.setter - def prefix_ns_integer(self, value): - """Sets the prefix_ns_integer of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_integer', value) - - @property - def prefix_ns_boolean(self): - """Gets the prefix_ns_boolean of this XmlItem. # noqa: E501 - - Returns: - (bool): The prefix_ns_boolean of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_boolean') - - @prefix_ns_boolean.setter - def prefix_ns_boolean(self, value): - """Sets the prefix_ns_boolean of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_boolean', value) - - @property - def prefix_ns_array(self): - """Gets the prefix_ns_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The prefix_ns_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_array') - - @prefix_ns_array.setter - def prefix_ns_array(self, value): - """Sets the prefix_ns_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_array', value) - - @property - def prefix_ns_wrapped_array(self): - """Gets the prefix_ns_wrapped_array of this XmlItem. # noqa: E501 - - Returns: - ([int]): The prefix_ns_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__get_item('prefix_ns_wrapped_array') - - @prefix_ns_wrapped_array.setter - def prefix_ns_wrapped_array(self, value): - """Sets the prefix_ns_wrapped_array of this XmlItem. # noqa: E501 - """ - return self.__set_item('prefix_ns_wrapped_array', value) - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, XmlItem): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in six.iteritems(self._data_store): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if (not six.PY3 and - len(types) == 2 and unicode in types): # noqa: F821 - vals_equal = ( - this_val.encode('utf-8') == that_val.encode('utf-8') - ) - if not vals_equal: - return False - return True - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + setattr(self, var_name, var_value) diff --git a/samples/client/petstore/python-experimental/test/test_child.py b/samples/client/petstore/python-experimental/test/test_child.py new file mode 100644 index 00000000000..96023582c4f --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChild(unittest.TestCase): + """Child unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChild(self): + """Test Child""" + + # make an instance of Child, a composed schema model + radio_waves = True + tele_vision = True + inter_net = True + child = petstore_api.Child( + radio_waves=radio_waves, + tele_vision=tele_vision, + inter_net=inter_net + ) + + # check its properties + self.assertEqual(child.radio_waves, radio_waves) + self.assertEqual(child.tele_vision, tele_vision) + self.assertEqual(child.inter_net, inter_net) + # access them with keys + self.assertEqual(child['radio_waves'], radio_waves) + self.assertEqual(child['tele_vision'], tele_vision) + self.assertEqual(child['inter_net'], inter_net) + # access them with getattr + self.assertEqual(getattr(child, 'radio_waves'), radio_waves) + self.assertEqual(getattr(child, 'tele_vision'), tele_vision) + self.assertEqual(getattr(child, 'inter_net'), inter_net) + + # check the model's to_dict result + self.assertEqual( + child.to_dict(), + { + 'radio_waves': radio_waves, + 'tele_vision': tele_vision, + 'inter_net': inter_net, + } + ) + + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + child['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(petstore_api.ApiKeyError): + setattr(child, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = child['invalid_variable'] + # with getattr + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = getattr(child, 'invalid_variable', 'some value') + + # make sure that the ModelComposed class properties are correct + # model.composed_schemas() stores the anyOf/allOf/oneOf info + self.assertEqual( + child._composed_schemas(), + { + 'anyOf': [], + 'allOf': [ + petstore_api.ChildAllOf, + petstore_api.Parent, + ], + 'oneOf': [], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in child._composed_instances: + if composed_instance.__class__ == petstore_api.Parent: + parent_instance = composed_instance + elif composed_instance.__class__ == petstore_api.ChildAllOf: + child_allof_instance = composed_instance + self.assertEqual( + child._composed_instances, + [child_allof_instance, parent_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + child._var_name_to_model_instances, + { + 'radio_waves': [child, parent_instance], + 'tele_vision': [child, parent_instance], + 'inter_net': [child, child_allof_instance] + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + child._additional_properties_model_instances, [] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + child_allof_instance.inter_net = False + with self.assertRaises(petstore_api.ApiValueError): + inter_net = child.inter_net + + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + child = petstore_api.Child( + radio_waves=radio_waves, + tele_vision=tele_vision, + inter_net=inter_net, + unknown_property='some value' + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_all_of.py b/samples/client/petstore/python-experimental/test/test_child_all_of.py new file mode 100644 index 00000000000..e3f14035f62 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_all_of.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildAllOf(unittest.TestCase): + """ChildAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildAllOf(self): + """Test ChildAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_cat.py b/samples/client/petstore/python-experimental/test/test_child_cat.py new file mode 100644 index 00000000000..c42c3b583aa --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_cat.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildCat(unittest.TestCase): + """ChildCat unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildCat(self): + """Test ChildCat""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildCat() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_cat_all_of.py b/samples/client/petstore/python-experimental/test/test_child_cat_all_of.py new file mode 100644 index 00000000000..3304a81a232 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_cat_all_of.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildCatAllOf(unittest.TestCase): + """ChildCatAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildCatAllOf(self): + """Test ChildCatAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildCatAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_dog.py b/samples/client/petstore/python-experimental/test/test_child_dog.py new file mode 100644 index 00000000000..9c56f27bbc4 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_dog.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildDog(unittest.TestCase): + """ChildDog unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildDog(self): + """Test ChildDog""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildDog() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_dog_all_of.py b/samples/client/petstore/python-experimental/test/test_child_dog_all_of.py new file mode 100644 index 00000000000..a9124db412b --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_dog_all_of.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildDogAllOf(unittest.TestCase): + """ChildDogAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildDogAllOf(self): + """Test ChildDogAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildDogAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_lizard.py b/samples/client/petstore/python-experimental/test/test_child_lizard.py new file mode 100644 index 00000000000..21ba88480aa --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_lizard.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildLizard(unittest.TestCase): + """ChildLizard unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildLizard(self): + """Test ChildLizard""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildLizard() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_child_lizard_all_of.py b/samples/client/petstore/python-experimental/test/test_child_lizard_all_of.py new file mode 100644 index 00000000000..824e376f855 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_child_lizard_all_of.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestChildLizardAllOf(unittest.TestCase): + """ChildLizardAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildLizardAllOf(self): + """Test ChildLizardAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ChildLizardAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_dog.py b/samples/client/petstore/python-experimental/test/test_dog.py index dc151f998dd..cb1f3230a06 100644 --- a/samples/client/petstore/python-experimental/test/test_dog.py +++ b/samples/client/petstore/python-experimental/test/test_dog.py @@ -5,7 +5,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - OpenAPI spec version: 1.0.0 + The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ @@ -15,8 +15,6 @@ from __future__ import absolute_import import unittest import petstore_api -from petstore_api.models.dog import Dog # noqa: E501 -from petstore_api.rest import ApiException class TestDog(unittest.TestCase): @@ -30,9 +28,111 @@ class TestDog(unittest.TestCase): def testDog(self): """Test Dog""" - # FIXME: construct object with mandatory attributes with example values - # model = petstore_api.models.dog.Dog() # noqa: E501 - pass + + # make an instance of dog, a composed schema model + class_name = 'Dog' + color = 'white' + breed = 'Jack Russel Terrier' + dog = petstore_api.Dog( + class_name=class_name, + color=color, + breed=breed + ) + + # check its properties + self.assertEqual(dog.class_name, class_name) + self.assertEqual(dog.color, color) + self.assertEqual(dog.breed, breed) + # access them with keys + self.assertEqual(dog['class_name'], class_name) + self.assertEqual(dog['color'], color) + self.assertEqual(dog['breed'], breed) + # access them with getattr + self.assertEqual(getattr(dog, 'class_name'), class_name) + self.assertEqual(getattr(dog, 'color'), color) + self.assertEqual(getattr(dog, 'breed'), breed) + + # check the model's to_dict result + self.assertEqual( + dog.to_dict(), + { + 'class_name': class_name, + 'color': color, + 'breed': breed, + } + ) + + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + dog['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(petstore_api.ApiKeyError): + setattr(dog, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = dog['invalid_variable'] + # with getattr + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = getattr(dog, 'invalid_variable', 'some value') + + # make sure that the ModelComposed class properties are correct + # model.composed_schemas() stores the anyOf/allOf/oneOf info + self.assertEqual( + dog._composed_schemas(), + { + 'anyOf': [], + 'allOf': [ + petstore_api.Animal, + petstore_api.DogAllOf, + ], + 'oneOf': [], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in dog._composed_instances: + if composed_instance.__class__ == petstore_api.Animal: + animal_instance = composed_instance + elif composed_instance.__class__ == petstore_api.DogAllOf: + dog_allof_instance = composed_instance + self.assertEqual( + dog._composed_instances, + [animal_instance, dog_allof_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + dog._var_name_to_model_instances, + { + 'breed': [dog, dog_allof_instance], + 'class_name': [dog, animal_instance], + 'color': [dog, animal_instance] + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + dog._additional_properties_model_instances, [] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + dog_allof_instance.breed = 'Golden Retriever' + with self.assertRaises(petstore_api.ApiValueError): + breed = dog.breed + + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + dog = petstore_api.Dog( + class_name=class_name, + color=color, + breed=breed, + unknown_property='some value' + ) if __name__ == '__main__': diff --git a/samples/client/petstore/python-experimental/test/test_grandparent.py b/samples/client/petstore/python-experimental/test/test_grandparent.py new file mode 100644 index 00000000000..44f594c086e --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_grandparent.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestGrandparent(unittest.TestCase): + """Grandparent unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testGrandparent(self): + """Test Grandparent""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Grandparent() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_grandparent_animal.py b/samples/client/petstore/python-experimental/test/test_grandparent_animal.py new file mode 100644 index 00000000000..dc0d300cdae --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_grandparent_animal.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestGrandparentAnimal(unittest.TestCase): + """GrandparentAnimal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testGrandparentAnimal(self): + """Test GrandparentAnimal""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.GrandparentAnimal() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_parent.py b/samples/client/petstore/python-experimental/test/test_parent.py new file mode 100644 index 00000000000..f719771bdcf --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_parent.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestParent(unittest.TestCase): + """Parent unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParent(self): + """Test Parent""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Parent() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_parent_all_of.py b/samples/client/petstore/python-experimental/test/test_parent_all_of.py new file mode 100644 index 00000000000..c1c152afe18 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_parent_all_of.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestParentAllOf(unittest.TestCase): + """ParentAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParentAllOf(self): + """Test ParentAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ParentAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test/test_parent_pet.py b/samples/client/petstore/python-experimental/test/test_parent_pet.py new file mode 100644 index 00000000000..b3ec1a94532 --- /dev/null +++ b/samples/client/petstore/python-experimental/test/test_parent_pet.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestParentPet(unittest.TestCase): + """ParentPet unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParentPet(self): + """Test ParentPet""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.ParentPet() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python-experimental/test_python2.sh b/samples/client/petstore/python-experimental/test_python2.sh index b68d0bd20a7..35de07deec7 100644 --- a/samples/client/petstore/python-experimental/test_python2.sh +++ b/samples/client/petstore/python-experimental/test_python2.sh @@ -8,16 +8,18 @@ DEACTIVE=false export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 +PYTHONPATH="$(which python)" ### set virtualenv if [ -z "$VIRTUAL_ENV" ]; then - virtualenv $VENV --no-site-packages --always-copy + virtualenv $VENV --python=$PYTHONPATH --no-site-packages --always-copy source $VENV/bin/activate DEACTIVE=true fi ### install dependencies pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT +pip install -r test-requirements.txt python setup.py develop ### run tests diff --git a/samples/client/petstore/python-experimental/tests/test_api_client.py b/samples/client/petstore/python-experimental/tests/test_api_client.py index ad50f186201..62d7b985954 100644 --- a/samples/client/petstore/python-experimental/tests/test_api_client.py +++ b/samples/client/petstore/python-experimental/tests/test_api_client.py @@ -141,8 +141,8 @@ class ApiClientTests(unittest.TestCase): # model pet_dict = {"id": 1, "name": "monkey", "category": {"id": 1, "name": "test category"}, - "tags": [{"id": 1, "name": "test tag1"}, - {"id": 2, "name": "test tag2"}], + "tags": [{"id": 1, "fullName": "test tag1"}, + {"id": 2, "fullName": "test tag2"}], "status": "available", "photoUrls": ["http://foo.bar.com/3", "http://foo.bar.com/4"]} @@ -154,10 +154,10 @@ class ApiClientTests(unittest.TestCase): pet.category = cate tag1 = petstore_api.Tag() tag1.id = pet_dict["tags"][0]["id"] - tag1.name = pet_dict["tags"][0]["name"] + tag1.full_name = pet_dict["tags"][0]["fullName"] tag2 = petstore_api.Tag() tag2.id = pet_dict["tags"][1]["id"] - tag2.name = pet_dict["tags"][1]["name"] + tag2.full_name = pet_dict["tags"][1]["fullName"] pet.tags = [tag1, tag2] pet.status = pet_dict["status"] diff --git a/samples/client/petstore/python-experimental/tests/test_api_exception.py b/samples/client/petstore/python-experimental/tests/test_api_exception.py index a05c3e902c5..026ba5bd79c 100644 --- a/samples/client/petstore/python-experimental/tests/test_api_exception.py +++ b/samples/client/petstore/python-experimental/tests/test_api_exception.py @@ -31,7 +31,7 @@ class ApiExceptionTests(unittest.TestCase): self.category.name = "dog" self.tag = petstore_api.Tag() self.tag.id = id_gen() - self.tag.name = "blank" + self.tag.full_name = "blank" self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"]) self.pet.id = id_gen() self.pet.status = "sold" diff --git a/samples/client/petstore/python-experimental/tests/test_deserialization.py b/samples/client/petstore/python-experimental/tests/test_deserialization.py index 9ab64b04bba..8ebeb1751ce 100644 --- a/samples/client/petstore/python-experimental/tests/test_deserialization.py +++ b/samples/client/petstore/python-experimental/tests/test_deserialization.py @@ -28,6 +28,7 @@ from petstore_api.exceptions import ( from petstore_api.model_utils import ( file_type, int, + model_to_dict, str, ) @@ -87,7 +88,7 @@ class DeserializationTests(unittest.TestCase): "tags": [ { "id": 0, - "name": "string" + "fullName": "string" } ], "status": "available" @@ -114,7 +115,25 @@ class DeserializationTests(unittest.TestCase): deserialized = self.deserialize(response, ({str: (petstore_api.Animal,)},), True) self.assertTrue(isinstance(deserialized, dict)) - self.assertTrue(isinstance(deserialized['dog'], petstore_api.Dog)) + dog = deserialized['dog'] + self.assertTrue(isinstance(dog, petstore_api.Dog)) + self.assertEqual(dog.class_name, "Dog") + self.assertEqual(dog.color, "white") + self.assertEqual(dog.breed, "Jack Russel Terrier") + + def test_deserialize_lizard(self): + """ deserialize ChildLizard, use discriminator""" + data = { + "pet_type": "ChildLizard", + "lovesRocks": True + } + response = MockResponse(data=json.dumps(data)) + + lizard = self.deserialize(response, + (petstore_api.ParentPet,), True) + self.assertTrue(isinstance(lizard, petstore_api.ChildLizard)) + self.assertEqual(lizard.pet_type, "ChildLizard") + self.assertEqual(lizard.loves_rocks, True) def test_deserialize_dict_str_int(self): """ deserialize dict(str, int) """ @@ -166,7 +185,7 @@ class DeserializationTests(unittest.TestCase): "tags": [ { "id": 0, - "name": "string" + "fullName": "string" } ], "status": "available" @@ -180,7 +199,7 @@ class DeserializationTests(unittest.TestCase): self.assertTrue(isinstance(deserialized.category, petstore_api.Category)) self.assertEqual(deserialized.category.name, "string") self.assertTrue(isinstance(deserialized.tags, list)) - self.assertEqual(deserialized.tags[0].name, "string") + self.assertEqual(deserialized.tags[0].full_name, "string") def test_deserialize_list_of_pet(self): """ deserialize list[Pet] """ @@ -198,7 +217,7 @@ class DeserializationTests(unittest.TestCase): "tags": [ { "id": 0, - "name": "string" + "fullName": "string" } ], "status": "available" @@ -216,7 +235,7 @@ class DeserializationTests(unittest.TestCase): "tags": [ { "id": 0, - "name": "string" + "fullName": "string" } ], "status": "available" diff --git a/samples/client/petstore/python-tornado/README.md b/samples/client/petstore/python-tornado/README.md index 8534592c150..b92f4eecf8d 100644 --- a/samples/client/petstore/python-tornado/README.md +++ b/samples/client/petstore/python-tornado/README.md @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import petstore_api +import petstore_api ``` ### Setuptools diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index 9a0c95c9045..f6f48362e57 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -300,41 +300,37 @@ class Configuration(object): } ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 8534592c150..b92f4eecf8d 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import petstore_api +import petstore_api ``` ### Setuptools diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 9a0c95c9045..f6f48362e57 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -300,41 +300,37 @@ class Configuration(object): } ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/samples/client/petstore/swift4/default/.openapi-generator/VERSION b/samples/client/petstore/swift4/default/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/default/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/default/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/default/Package.swift b/samples/client/petstore/swift4/default/Package.swift index a847bc5077d..e5c5f0f33b8 100644 --- a/samples/client/petstore/swift4/default/Package.swift +++ b/samples/client/petstore/swift4/default/Package.swift @@ -9,11 +9,11 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -22,6 +22,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1e6b7fc02c2..02e24286e3c 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class AnotherFakeAPI { /** To test special tags @@ -16,7 +14,7 @@ open class AnotherFakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 0bdeee0b2cb..b0b394aa06e 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,15 +7,13 @@ import Foundation - - open class FakeAPI { /** - parameter body: (body) Input boolean as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?,_ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -44,7 +42,7 @@ open class FakeAPI { - parameter body: (body) Input composite as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -73,7 +71,7 @@ open class FakeAPI { - parameter body: (body) Input number as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?,_ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -102,7 +100,7 @@ open class FakeAPI { - parameter body: (body) Input string as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -131,8 +129,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -165,8 +163,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -202,7 +200,7 @@ open class FakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -246,8 +244,8 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -282,7 +280,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -301,7 +299,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -389,8 +387,8 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -416,19 +414,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -453,8 +451,8 @@ open class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -478,13 +476,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -504,8 +502,8 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -520,7 +518,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -539,8 +537,8 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -559,14 +557,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 822a371cef3..060d434fbf2 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,8 +7,6 @@ import Foundation - - open class FakeClassnameTags123API { /** To test class name in snake case @@ -16,7 +14,7 @@ open class FakeClassnameTags123API { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index cc4397947d1..fe75962a72c 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class PetAPI { /** Add a new pet to the store @@ -16,8 +14,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -54,8 +52,8 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -80,8 +78,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -108,7 +106,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(response?.body, error) } @@ -127,8 +125,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -145,7 +143,7 @@ open class PetAPI { - parameter tags: (query) Tags to filter by - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(response?.body, error) } @@ -164,8 +162,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -182,7 +180,7 @@ open class PetAPI { - parameter petId: (path) ID of pet to return - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -204,8 +202,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -219,8 +217,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -258,8 +256,8 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -285,14 +283,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -308,7 +306,7 @@ open class PetAPI { - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(response?.body, error) } @@ -331,14 +329,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -354,7 +352,7 @@ open class PetAPI { - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in completion(response?.body, error) } @@ -377,14 +375,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index b62f18f3f02..d5f627df52a 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class StoreAPI { /** Delete purchase order by ID @@ -16,8 +14,8 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -39,8 +37,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -53,7 +51,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { + open class func getInventory(completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } @@ -68,14 +66,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -86,7 +84,7 @@ open class StoreAPI { - parameter orderId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -105,8 +103,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -120,7 +118,7 @@ open class StoreAPI { - parameter body: (body) order placed for purchasing the pet - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 0e2d140e037..ef4f971a91e 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class UserAPI { /** Create user @@ -16,8 +14,8 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUser(body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -51,8 +49,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -85,8 +83,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -119,8 +117,8 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -142,8 +140,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -157,7 +155,7 @@ open class UserAPI { - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + open class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in completion(response?.body, error) } @@ -175,8 +173,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -191,7 +189,7 @@ open class UserAPI { - parameter password: (query) The password for login in clear text - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in completion(response?.body, error) } @@ -208,11 +206,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -226,8 +224,8 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + open class func logoutUser(completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -244,8 +242,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -260,8 +258,8 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index fdbe7f72017..27cf29c6560 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 1f948ae12f7..74fcfcf2ad4 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 46d4828ceb6..5ed9f31e2a3 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 087b65ef044..7ab887f3113 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index bcd0a62e010..eb8f7e5e197 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ed63186cc45..492c1228008 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 74ec3850fb2..6db9b34d183 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 260526eb804..20bd6d103b3 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 06d5ac3c87b..43c4891e1e2 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index d38c8953f0f..a6e1b1d2e5e 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e943c40a8c4..af60a550bb1 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8277746be90..4dd8a9a9f5a 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b936721e454..bf0006e1a26 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d7bf3f5b13e..602a2a6d185 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift index d71e55e3c19..79f271ed735 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/nonPublicApi/.openapi-generator/VERSION b/samples/client/petstore/swift4/nonPublicApi/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/nonPublicApi/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/nonPublicApi/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/nonPublicApi/Package.swift b/samples/client/petstore/swift4/nonPublicApi/Package.swift index a847bc5077d..e5c5f0f33b8 100644 --- a/samples/client/petstore/swift4/nonPublicApi/Package.swift +++ b/samples/client/petstore/swift4/nonPublicApi/Package.swift @@ -9,11 +9,11 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -22,6 +22,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 93b30800826..6f36b224248 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation internal struct APIHelper { - internal static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + internal static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ internal struct APIHelper { return destination } - internal static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + internal static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - internal static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + internal static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ internal struct APIHelper { return source } - internal static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + internal static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ internal struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift index 04afd1c3764..4e09f94504f 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation internal class PetstoreClientAPI { internal static var basePath = "http://petstore.swagger.io:80/v2" internal static var credential: URLCredential? - internal static var customHeaders: [String:String] = [:] + internal static var customHeaders: [String: String] = [:] internal static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() internal static var apiResponseQueue: DispatchQueue = .main } internal class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - internal let parameters: [String:Any]? + var headers: [String: String] + internal let parameters: [String: Any]? internal let isBody: Bool internal let method: String internal let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - internal var onProgressReady: ((Progress) -> ())? + internal var onProgressReady: ((Progress) -> Void)? - required internal init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required internal init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ internal class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - internal func addHeaders(_ aHeaders:[String:String]) { + internal func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ internal class RequestBuilder { internal protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 015f165c9f9..9126bafa69c 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,8 +7,6 @@ import Foundation - - internal class AnotherFakeAPI { /** To test special tags @@ -16,7 +14,7 @@ internal class AnotherFakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - internal class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + internal class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index fa8cd0b7626..28a05b008c6 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,15 +7,13 @@ import Foundation - - internal class FakeAPI { /** - parameter body: (body) Input boolean as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?,_ error: Error?) -> Void)) { + internal class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -44,7 +42,7 @@ internal class FakeAPI { - parameter body: (body) Input composite as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -73,7 +71,7 @@ internal class FakeAPI { - parameter body: (body) Input number as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?,_ error: Error?) -> Void)) { + internal class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -102,7 +100,7 @@ internal class FakeAPI { - parameter body: (body) Input string as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + internal class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -131,8 +129,8 @@ internal class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -165,8 +163,8 @@ internal class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + internal class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -202,7 +200,7 @@ internal class FakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + internal class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -230,15 +228,15 @@ internal class FakeAPI { /** Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - - parameter number: (form) None - - parameter double: (form) None - - parameter patternWithoutDelimiter: (form) None - - parameter byte: (form) None - parameter integer: (form) None (optional) - parameter int32: (form) None (optional) - parameter int64: (form) None (optional) + - parameter number: (form) None - parameter float: (form) None (optional) + - parameter double: (form) None - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None - parameter binary: (form) None (optional) - parameter date: (form) None (optional) - parameter dateTime: (form) None (optional) @@ -246,8 +244,8 @@ internal class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -263,15 +261,15 @@ internal class FakeAPI { - BASIC: - type: http - name: http_basic_test - - parameter number: (form) None - - parameter double: (form) None - - parameter patternWithoutDelimiter: (form) None - - parameter byte: (form) None - parameter integer: (form) None (optional) - parameter int32: (form) None (optional) - parameter int64: (form) None (optional) + - parameter number: (form) None - parameter float: (form) None (optional) + - parameter double: (form) None - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None - parameter binary: (form) None (optional) - parameter date: (form) None (optional) - parameter dateTime: (form) None (optional) @@ -279,10 +277,10 @@ internal class FakeAPI { - parameter callback: (form) None (optional) - returns: RequestBuilder */ - internal class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + internal class func testEndpointParametersWithRequestBuilder(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -301,7 +299,7 @@ internal class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -389,8 +387,8 @@ internal class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -416,19 +414,19 @@ internal class FakeAPI { internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -453,8 +451,8 @@ internal class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -478,13 +476,13 @@ internal class FakeAPI { internal class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -504,8 +502,8 @@ internal class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - internal class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + internal class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -520,7 +518,7 @@ internal class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - internal class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + internal class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -539,8 +537,8 @@ internal class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - internal class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + internal class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -559,14 +557,14 @@ internal class FakeAPI { internal class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 47ea5157ae2..e4c221d8cb4 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,8 +7,6 @@ import Foundation - - internal class FakeClassnameTags123API { /** To test class name in snake case @@ -16,7 +14,7 @@ internal class FakeClassnameTags123API { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + internal class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f290aaea0c5..88b3b5b893c 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,8 +7,6 @@ import Foundation - - internal class PetAPI { /** Add a new pet to the store @@ -16,8 +14,8 @@ internal class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - internal class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func addPet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -50,12 +48,12 @@ internal class PetAPI { /** Deletes a pet - - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete - parameter completion: completion handler to receive the data and the error objects */ - internal class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + internal class func deletePet(apiKey: String? = nil, petId: Int64, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(apiKey: apiKey, petId: petId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -70,18 +68,18 @@ internal class PetAPI { - OAuth: - type: oauth2 - name: petstore_auth - - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete - returns: RequestBuilder */ - internal class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + internal class func deletePetWithRequestBuilder(apiKey: String? = nil, petId: Int64) -> RequestBuilder { var path = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -108,7 +106,7 @@ internal class PetAPI { - parameter status: (query) Status values that need to be considered for filter - parameter completion: completion handler to receive the data and the error objects */ - internal class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + internal class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(response?.body, error) } @@ -127,8 +125,8 @@ internal class PetAPI { internal class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -145,7 +143,7 @@ internal class PetAPI { - parameter tags: (query) Tags to filter by - parameter completion: completion handler to receive the data and the error objects */ - internal class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + internal class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(response?.body, error) } @@ -164,8 +162,8 @@ internal class PetAPI { internal class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -182,7 +180,7 @@ internal class PetAPI { - parameter petId: (path) ID of pet to return - parameter completion: completion handler to receive the data and the error objects */ - internal class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + internal class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -204,8 +202,8 @@ internal class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -219,8 +217,8 @@ internal class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func updatePet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -258,8 +256,8 @@ internal class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -285,14 +283,14 @@ internal class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -308,7 +306,7 @@ internal class PetAPI { - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(response?.body, error) } @@ -331,14 +329,14 @@ internal class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -350,12 +348,12 @@ internal class PetAPI { uploads an image (required) - parameter petId: (path) ID of pet to update - - parameter requiredFile: (form) file to upload - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { - uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in + internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + uploadFileWithRequiredFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile).execute { (response, error) -> Void in completion(response?.body, error) } } @@ -367,24 +365,24 @@ internal class PetAPI { - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet to update - - parameter requiredFile: (form) file to upload - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload - returns: RequestBuilder */ - internal class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { + internal class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL) -> RequestBuilder { var path = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index cbf018279ac..cfd546b9095 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,6 @@ import Foundation - - internal class StoreAPI { /** Delete purchase order by ID @@ -16,8 +14,8 @@ internal class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + internal class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -39,8 +37,8 @@ internal class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -53,7 +51,7 @@ internal class StoreAPI { - parameter completion: completion handler to receive the data and the error objects */ - internal class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { + internal class func getInventory(completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } @@ -68,14 +66,14 @@ internal class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - internal class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + internal class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -86,7 +84,7 @@ internal class StoreAPI { - parameter orderId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ - internal class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + internal class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -105,8 +103,8 @@ internal class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -120,7 +118,7 @@ internal class StoreAPI { - parameter body: (body) order placed for purchasing the pet - parameter completion: completion handler to receive the data and the error objects */ - internal class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + internal class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 7d85f91c685..76d77e2cf33 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,6 @@ import Foundation - - internal class UserAPI { /** Create user @@ -16,8 +14,8 @@ internal class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func createUser(body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -51,8 +49,8 @@ internal class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -85,8 +83,8 @@ internal class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + internal class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -119,8 +117,8 @@ internal class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + internal class func deleteUser(username: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -142,8 +140,8 @@ internal class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -157,7 +155,7 @@ internal class UserAPI { - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + internal class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in completion(response?.body, error) } @@ -175,8 +173,8 @@ internal class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -191,7 +189,7 @@ internal class UserAPI { - parameter password: (query) The password for login in clear text - parameter completion: completion handler to receive the data and the error objects */ - internal class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + internal class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in completion(response?.body, error) } @@ -208,11 +206,11 @@ internal class UserAPI { internal class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -226,8 +224,8 @@ internal class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - internal class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + internal class func logoutUser(completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -244,8 +242,8 @@ internal class UserAPI { internal class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -260,8 +258,8 @@ internal class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - internal class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + internal class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index aef46f478f5..691163584e0 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() internal class AlamofireRequestBuilder: RequestBuilder { - required internal init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required internal init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ internal class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - internal func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + internal func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override internal func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ internal class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ internal enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -internal class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +internal class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ internal class AlamofireDecodableRequestBuilder: AlamofireRequestBu return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index c0cfcf2343e..86c1f884b2e 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ internal class CodableHelper { set { self.customJSONEncoder = newValue } } - internal class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + internal class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ internal class CodableHelper { return (returnedDecodable, returnedError) } - internal class func encode(_ value: T) -> EncodeResult where T : Encodable { + internal class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ internal class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8cca4558325..bfcf939d4bb 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation internal class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. internal static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e6ecffbab5d..66f407c1c5f 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - internal mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + internal mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - internal mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + internal mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - internal mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + internal mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - internal mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + internal mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - internal func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + internal func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - internal func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + internal func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - internal func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + internal func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index cb5959f0fa4..bd9f3a2ed0d 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ internal struct JSONDataEncoding: ParameterEncoding { } internal static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 22b34d0a00c..fe09f37cd02 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire internal class JSONEncodingHelper { - internal class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + internal class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ internal class JSONEncodingHelper { } internal class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ internal class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 336c8848ba9..5c253abc2c4 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -internal enum ErrorResponse : Error { +internal enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ internal class Response { internal convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index b708182c2e2..203d2c1a931 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - internal struct AdditionalPropertiesClass: Codable { - internal var mapString: [String:String]? - internal var mapMapString: [String:[String:String]]? + internal var mapString: [String: String]? + internal var mapMapString: [String: [String: String]]? - internal init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + internal init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index a1ea3ef6cca..ada7f86de50 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Animal: Codable { internal var className: String diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index 9c570350859..3ebe9e9a5de 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - internal typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index b229f5868b6..b60d8999b4b 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - internal struct ApiResponse: Codable { internal var code: Int? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 2abe39f7ea8..ef26025dcd8 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - internal struct ArrayOfArrayOfNumberOnly: Codable { internal var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ internal struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 595d04d352f..1147e9394c7 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - internal struct ArrayOfNumberOnly: Codable { internal var arrayNumber: [Double]? @@ -16,7 +15,7 @@ internal struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 1a0e3e90f58..ffbc3ebc736 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - internal struct ArrayTest: Codable { internal var arrayOfString: [String]? @@ -20,7 +19,7 @@ internal struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b036619b933..52cdbb01be7 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Capitalization: Codable { internal var smallCamel: String? @@ -27,7 +26,7 @@ internal struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 679fcc0357d..8a603dee5f1 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Cat: Codable { internal var className: String diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 58f45d48e1b..45b7dbb26dc 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - internal struct CatAllOf: Codable { internal var declawed: Bool? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4a0455e474d..849bf788dfb 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Category: Codable { internal var id: Int64? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8ef88c02834..ddee836043f 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Client: Codable { internal var client: String? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 60062138c76..6b5250de4a4 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Dog: Codable { internal var className: String diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index a03d747850c..ef3ff7f1d78 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - internal struct DogAllOf: Codable { internal var breed: String? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 54384f7d3e2..b84e5e2e1e2 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - internal struct EnumArrays: Codable { internal enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ internal struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 432332510cf..2520f9bd859 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - internal enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 6717986da0c..eba9a8056ef 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - internal struct EnumTest: Codable { internal enum EnumString: String, Codable { @@ -42,7 +41,7 @@ internal struct EnumTest: Codable { self.outerEnum = outerEnum } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 5540b5e6d1f..e478e6c4b7d 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - internal struct FileSchemaTestClass: Codable { internal var file: File? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 8976492cd66..23395c93b56 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - internal struct FormatTest: Codable { internal var integer: Int? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 179d626b643..831963ba2ed 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - internal struct HasOnlyReadOnly: Codable { internal var bar: String? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 6937817a62c..ba9579996d1 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - internal struct List: Codable { internal var _123list: String? @@ -16,7 +15,7 @@ internal struct List: Codable { self._123list = _123list } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 589ac492910..f59541f7675 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - internal struct MapTest: Codable { internal enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - internal var mapMapOfString: [String:[String:String]]? - internal var mapOfEnumString: [String:String]? - internal var directMap: [String:Bool]? + internal var mapMapOfString: [String: [String: String]]? + internal var mapOfEnumString: [String: String]? + internal var directMap: [String: Bool]? internal var indirectMap: StringBooleanMap? - internal init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + internal init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ab4634e3beb..c71bb9256b0 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable { internal var uuid: UUID? internal var dateTime: Date? - internal var map: [String:Animal]? + internal var map: [String: Animal]? - internal init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + internal init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 01c3b342b5c..bd288322e75 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ internal struct Model200Response: Codable { self._class = _class } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 1b984c42d44..85a5b795395 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ internal struct Name: Codable { self._123number = _123number } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index e60030be0ec..7dbe99f1426 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - internal struct NumberOnly: Codable { internal var justNumber: Double? @@ -16,7 +15,7 @@ internal struct NumberOnly: Codable { self.justNumber = justNumber } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 96c522f3635..7f575485bf7 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Order: Codable { internal enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index a6d4cd98364..04fbad30ef7 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - internal struct OuterComposite: Codable { internal var myNumber: Double? @@ -20,7 +19,7 @@ internal struct OuterComposite: Codable { self.myBoolean = myBoolean } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 790fd71c13d..fd2d4b4cdda 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - internal enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 4104dce89df..951f5929f92 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Pet: Codable { internal enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 0bcec482f28..d02c6cc5fd9 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - internal struct ReadOnlyFirst: Codable { internal var bar: String? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 8303fc95d1c..2e28c04ef55 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ internal struct Return: Codable { self._return = _return } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 993d472d0f3..b35724b1ca7 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - internal struct SpecialModelName: Codable { internal var specialPropertyName: Int64? @@ -16,7 +15,7 @@ internal struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 7d465fa0f5d..dc3d00e1301 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - internal struct StringBooleanMap: Codable { - - internal var additionalProperties: [String:Bool] = [:] + internal var additionalProperties: [String: Bool] = [:] internal subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ internal struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 4dd149f0cc6..1e4de951fb2 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - internal struct Tag: Codable { internal var id: Int64? diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 6d911687757..0cff6b6a2f8 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - internal struct TypeHolderDefault: Codable { internal var stringItem: String = "what" @@ -24,7 +23,7 @@ internal struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index eeea24d466f..5d8f63dfe4a 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - internal struct TypeHolderExample: Codable { internal var stringItem: String @@ -24,7 +23,7 @@ internal struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - internal enum CodingKeys: String, CodingKey { + internal enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 1840f84acf7..ada8a7f82d9 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - internal struct User: Codable { internal var id: Int64? diff --git a/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md index 29181bd6456..f8e42ac4df8 100644 --- a/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md @@ -364,7 +364,7 @@ No authorization required # **testEndpointParameters** ```swift - internal class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -376,15 +376,15 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let number = 987 // Double | None -let double = 987 // Double | None -let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) +let number = 987 // Double | None let float = 987 // Float | None (optional) +let double = 987 // Double | None let string = "string_example" // String | None (optional) +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = 987 // Data | None let binary = URL(string: "https://example.com")! // URL | None (optional) let date = Date() // Date | None (optional) let dateTime = Date() // Date | None (optional) @@ -392,7 +392,7 @@ let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in +FakeAPI.testEndpointParameters(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) return @@ -408,15 +408,15 @@ FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDel Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **Double** | None | - **double** | **Double** | None | - **patternWithoutDelimiter** | **String** | None | - **byte** | **Data** | None | **integer** | **Int** | None | [optional] **int32** | **Int** | None | [optional] **int64** | **Int64** | None | [optional] + **number** | **Double** | None | **float** | **Float** | None | [optional] + **double** | **Double** | None | **string** | **String** | None | [optional] + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | **binary** | **URL** | None | [optional] **date** | **Date** | None | [optional] **dateTime** | **Date** | None | [optional] diff --git a/samples/client/petstore/swift4/nonPublicApi/docs/PetAPI.md b/samples/client/petstore/swift4/nonPublicApi/docs/PetAPI.md index ddafde461eb..8fd9872c0e9 100644 --- a/samples/client/petstore/swift4/nonPublicApi/docs/PetAPI.md +++ b/samples/client/petstore/swift4/nonPublicApi/docs/PetAPI.md @@ -65,7 +65,7 @@ Void (empty response body) # **deletePet** ```swift - internal class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + internal class func deletePet(apiKey: String? = nil, petId: Int64, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` Deletes a pet @@ -75,11 +75,11 @@ Deletes a pet // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let petId = 987 // Int64 | Pet id to delete let apiKey = "apiKey_example" // String | (optional) +let petId = 987 // Int64 | Pet id to delete // Deletes a pet -PetAPI.deletePet(petId: petId, apiKey: apiKey) { (response, error) in +PetAPI.deletePet(apiKey: apiKey, petId: petId) { (response, error) in guard error == nil else { print(error) return @@ -95,8 +95,8 @@ PetAPI.deletePet(petId: petId, apiKey: apiKey) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Int64** | Pet id to delete | **apiKey** | **String** | | [optional] + **petId** | **Int64** | Pet id to delete | ### Return type @@ -417,7 +417,7 @@ Name | Type | Description | Notes # **uploadFileWithRequiredFile** ```swift - internal class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) + internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) ``` uploads an image (required) @@ -428,11 +428,11 @@ uploads an image (required) import PetstoreClient let petId = 987 // Int64 | ID of pet to update -let requiredFile = URL(string: "https://example.com")! // URL | file to upload let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let requiredFile = URL(string: "https://example.com")! // URL | file to upload // uploads an image (required) -PetAPI.uploadFileWithRequiredFile(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata) { (response, error) in +PetAPI.uploadFileWithRequiredFile(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile) { (response, error) in guard error == nil else { print(error) return @@ -449,8 +449,8 @@ PetAPI.uploadFileWithRequiredFile(petId: petId, requiredFile: requiredFile, addi Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **Int64** | ID of pet to update | - **requiredFile** | **URL** | file to upload | **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **requiredFile** | **URL** | file to upload | ### Return type diff --git a/samples/client/petstore/swift4/objcCompatible/.openapi-generator/VERSION b/samples/client/petstore/swift4/objcCompatible/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/objcCompatible/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/objcCompatible/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/objcCompatible/Package.swift b/samples/client/petstore/swift4/objcCompatible/Package.swift index a847bc5077d..e5c5f0f33b8 100644 --- a/samples/client/petstore/swift4/objcCompatible/Package.swift +++ b/samples/client/petstore/swift4/objcCompatible/Package.swift @@ -9,11 +9,11 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -22,6 +22,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1e6b7fc02c2..02e24286e3c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class AnotherFakeAPI { /** To test special tags @@ -16,7 +14,7 @@ open class AnotherFakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 0bdeee0b2cb..b0b394aa06e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,15 +7,13 @@ import Foundation - - open class FakeAPI { /** - parameter body: (body) Input boolean as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?,_ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -44,7 +42,7 @@ open class FakeAPI { - parameter body: (body) Input composite as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -73,7 +71,7 @@ open class FakeAPI { - parameter body: (body) Input number as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?,_ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -102,7 +100,7 @@ open class FakeAPI { - parameter body: (body) Input string as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -131,8 +129,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -165,8 +163,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -202,7 +200,7 @@ open class FakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -246,8 +244,8 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -282,7 +280,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -301,7 +299,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -389,8 +387,8 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -416,19 +414,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -453,8 +451,8 @@ open class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -478,13 +476,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -504,8 +502,8 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -520,7 +518,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -539,8 +537,8 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -559,14 +557,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 822a371cef3..060d434fbf2 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,8 +7,6 @@ import Foundation - - open class FakeClassnameTags123API { /** To test class name in snake case @@ -16,7 +14,7 @@ open class FakeClassnameTags123API { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index cc4397947d1..fe75962a72c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class PetAPI { /** Add a new pet to the store @@ -16,8 +14,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -54,8 +52,8 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -80,8 +78,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -108,7 +106,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(response?.body, error) } @@ -127,8 +125,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -145,7 +143,7 @@ open class PetAPI { - parameter tags: (query) Tags to filter by - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(response?.body, error) } @@ -164,8 +162,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -182,7 +180,7 @@ open class PetAPI { - parameter petId: (path) ID of pet to return - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -204,8 +202,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -219,8 +217,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -258,8 +256,8 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -285,14 +283,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -308,7 +306,7 @@ open class PetAPI { - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(response?.body, error) } @@ -331,14 +329,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -354,7 +352,7 @@ open class PetAPI { - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in completion(response?.body, error) } @@ -377,14 +375,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index b62f18f3f02..d5f627df52a 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class StoreAPI { /** Delete purchase order by ID @@ -16,8 +14,8 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -39,8 +37,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -53,7 +51,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { + open class func getInventory(completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } @@ -68,14 +66,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -86,7 +84,7 @@ open class StoreAPI { - parameter orderId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -105,8 +103,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -120,7 +118,7 @@ open class StoreAPI { - parameter body: (body) order placed for purchasing the pet - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 0e2d140e037..ef4f971a91e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class UserAPI { /** Create user @@ -16,8 +14,8 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUser(body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -51,8 +49,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -85,8 +83,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -119,8 +117,8 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -142,8 +140,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -157,7 +155,7 @@ open class UserAPI { - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + open class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in completion(response?.body, error) } @@ -175,8 +173,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -191,7 +189,7 @@ open class UserAPI { - parameter password: (query) The password for login in clear text - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in completion(response?.body, error) } @@ -208,11 +206,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -226,8 +224,8 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + open class func logoutUser(completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -244,8 +242,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -260,8 +258,8 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index 57bab28b199..27cf29c6560 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ open class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 1f948ae12f7..74fcfcf2ad4 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 46d4828ceb6..5ed9f31e2a3 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c246fc1e29e..7d819cbcc8f 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index fe7b9decd6d..abcd82b0783 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var _id: Int64? @@ -18,7 +17,7 @@ public struct Category: Codable { self.name = name } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _id = "id" case name } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ed63186cc45..492c1228008 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 74ec3850fb2..6db9b34d183 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 260526eb804..20bd6d103b3 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 06d5ac3c87b..43c4891e1e2 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 0d08d5fdf8d..f2b7565e2d9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { @@ -32,7 +31,7 @@ public struct Order: Codable { self.complete = complete } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _id = "id" case petId case quantity diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 3d0d5a75195..971ce9d4db6 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { @@ -32,7 +31,7 @@ public struct Pet: Codable { self.status = status } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _id = "id" case category case name diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 853e9af2221..83efe72b8a4 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var _id: Int64? @@ -18,7 +17,7 @@ public struct Tag: Codable { self.name = name } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _id = "id" case name } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b936721e454..bf0006e1a26 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d7bf3f5b13e..602a2a6d185 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift index dec4a9ce4bd..7d6b24b9e10 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var _id: Int64? @@ -31,7 +30,7 @@ public struct User: Codable { self.userStatus = userStatus } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _id = "id" case username case firstName diff --git a/samples/client/petstore/swift4/promisekitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift4/promisekitLibrary/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/promisekitLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/promisekitLibrary/Package.swift b/samples/client/petstore/swift4/promisekitLibrary/Package.swift index fbf22f5f823..7ba5c67b456 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/Package.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/Package.swift @@ -9,12 +9,12 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.11.0"), + .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.11.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -23,6 +23,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire", "PromiseKit"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 7399d2c1c56..5b75a4da29f 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class AnotherFakeAPI { /** To test special tags diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 3b580e45507..39c419674ba 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class FakeAPI { /** @@ -166,7 +164,7 @@ open class FakeAPI { */ open class func testBodyWithFileSchema( body: FileSchemaTestClass) -> Promise { let deferred = Promise.pending() - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -200,9 +198,9 @@ open class FakeAPI { - parameter body: (body) - returns: Promise */ - open class func testBodyWithQueryParams( query: String, body: User) -> Promise { + open class func testBodyWithQueryParams( query: String, body: User) -> Promise { let deferred = Promise.pending() - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -291,9 +289,9 @@ open class FakeAPI { - parameter callback: (form) None (optional) - returns: Promise */ - open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Promise { + open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Promise { let deferred = Promise.pending() - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -329,7 +327,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -348,7 +346,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -436,9 +434,9 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: Promise */ - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise { + open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise { let deferred = Promise.pending() - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -465,19 +463,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -502,9 +500,9 @@ open class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - returns: Promise */ - open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> Promise { + open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> Promise { let deferred = Promise.pending() - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -529,13 +527,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -555,9 +553,9 @@ open class FakeAPI { - parameter param: (body) request body - returns: Promise */ - open class func testInlineAdditionalProperties( param: [String:String]) -> Promise { + open class func testInlineAdditionalProperties( param: [String: String]) -> Promise { let deferred = Promise.pending() - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -573,7 +571,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -592,9 +590,9 @@ open class FakeAPI { - parameter param2: (form) field2 - returns: Promise */ - open class func testJsonFormData( param: String, param2: String) -> Promise { + open class func testJsonFormData( param: String, param2: String) -> Promise { let deferred = Promise.pending() - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -614,14 +612,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index f43f705eb6f..574ec49021b 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class FakeClassnameTags123API { /** To test class name in snake case diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 02a5e5417a6..8d31c177eb9 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class PetAPI { /** Add a new pet to the store @@ -19,7 +17,7 @@ open class PetAPI { */ open class func addPet( body: Pet) -> Promise { let deferred = Promise.pending() - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -57,9 +55,9 @@ open class PetAPI { - parameter apiKey: (header) (optional) - returns: Promise */ - open class func deletePet( petId: Int64, apiKey: String? = nil) -> Promise { + open class func deletePet( petId: Int64, apiKey: String? = nil) -> Promise { let deferred = Promise.pending() - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -85,8 +83,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -140,8 +138,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -185,8 +183,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -233,8 +231,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -250,7 +248,7 @@ open class PetAPI { */ open class func updatePet( body: Pet) -> Promise { let deferred = Promise.pending() - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -289,9 +287,9 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - returns: Promise */ - open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil) -> Promise { + open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil) -> Promise { let deferred = Promise.pending() - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -318,14 +316,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -341,7 +339,7 @@ open class PetAPI { - parameter file: (form) file to upload (optional) - returns: Promise */ - open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> Promise { + open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> Promise { let deferred = Promise.pending() uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in if let error = error { @@ -372,14 +370,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -395,7 +393,7 @@ open class PetAPI { - parameter additionalMetadata: (form) Additional data to pass to server (optional) - returns: Promise */ - open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> Promise { + open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> Promise { let deferred = Promise.pending() uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in if let error = error { @@ -426,14 +424,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index eeb3548e88a..685827cebe6 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class StoreAPI { /** Delete purchase order by ID @@ -19,7 +17,7 @@ open class StoreAPI { */ open class func deleteOrder( orderId: String) -> Promise { let deferred = Promise.pending() - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -42,8 +40,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -56,8 +54,8 @@ open class StoreAPI { - returns: Promise<[String:Int]> */ - open class func getInventory() -> Promise<[String:Int]> { - let deferred = Promise<[String:Int]>.pending() + open class func getInventory() -> Promise<[String: Int]> { + let deferred = Promise<[String: Int]>.pending() getInventoryWithRequestBuilder().execute { (response, error) -> Void in if let error = error { deferred.resolver.reject(error) @@ -79,14 +77,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -124,8 +122,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index ab269c05679..83f4674553c 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -8,8 +8,6 @@ import Foundation import PromiseKit - - open class UserAPI { /** Create user @@ -19,7 +17,7 @@ open class UserAPI { */ open class func createUser( body: User) -> Promise { let deferred = Promise.pending() - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -56,7 +54,7 @@ open class UserAPI { */ open class func createUsersWithArrayInput( body: [User]) -> Promise { let deferred = Promise.pending() - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -92,7 +90,7 @@ open class UserAPI { */ open class func createUsersWithListInput( body: [User]) -> Promise { let deferred = Promise.pending() - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -128,7 +126,7 @@ open class UserAPI { */ open class func deleteUser( username: String) -> Promise { let deferred = Promise.pending() - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -151,8 +149,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -192,8 +190,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -208,7 +206,7 @@ open class UserAPI { - parameter password: (query) The password for login in clear text - returns: Promise */ - open class func loginUser( username: String, password: String) -> Promise { + open class func loginUser( username: String, password: String) -> Promise { let deferred = Promise.pending() loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in if let error = error { @@ -233,11 +231,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -253,7 +251,7 @@ open class UserAPI { */ open class func logoutUser() -> Promise { let deferred = Promise.pending() - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { @@ -271,8 +269,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -287,9 +285,9 @@ open class UserAPI { - parameter body: (body) Updated user object - returns: Promise */ - open class func updateUser( username: String, body: User) -> Promise { + open class func updateUser( username: String, body: User) -> Promise { let deferred = Promise.pending() - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if let error = error { deferred.resolver.reject(error) } else { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index 57bab28b199..27cf29c6560 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ open class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 8278ae0f3b2..0ee7b7f0f6d 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -109,24 +109,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -136,7 +136,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -148,8 +148,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -158,8 +158,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -174,7 +174,7 @@ extension KeyedDecodingContainerProtocol { } extension RequestBuilder { - public func execute() -> Promise> { + public func execute() -> Promise> { let deferred = Promise>.pending() self.execute { (response: Response?, error: Error?) in if let response = response { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 46d4828ceb6..5ed9f31e2a3 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 087b65ef044..7ab887f3113 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index bcd0a62e010..eb8f7e5e197 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ed63186cc45..492c1228008 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 74ec3850fb2..6db9b34d183 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 260526eb804..20bd6d103b3 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 06d5ac3c87b..43c4891e1e2 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index d38c8953f0f..a6e1b1d2e5e 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e943c40a8c4..af60a550bb1 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8277746be90..4dd8a9a9f5a 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b936721e454..bf0006e1a26 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d7bf3f5b13e..602a2a6d185 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index d71e55e3c19..79f271ed735 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/resultLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift4/resultLibrary/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/resultLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/resultLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/resultLibrary/Package.swift b/samples/client/petstore/swift4/resultLibrary/Package.swift index a847bc5077d..e5c5f0f33b8 100644 --- a/samples/client/petstore/swift4/resultLibrary/Package.swift +++ b/samples/client/petstore/swift4/resultLibrary/Package.swift @@ -9,11 +9,11 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -22,6 +22,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 0cde67c7899..fb4bb8cfdb4 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class AnotherFakeAPI { /** To test special tags @@ -16,7 +14,7 @@ open class AnotherFakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index c9cdeca5743..c5d29842ad8 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,15 +7,13 @@ import Foundation - - open class FakeAPI { /** - parameter body: (body) Input boolean as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?,_ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -60,7 +58,7 @@ open class FakeAPI { - parameter body: (body) Input composite as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -105,7 +103,7 @@ open class FakeAPI { - parameter body: (body) Input number as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?,_ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -150,7 +148,7 @@ open class FakeAPI { - parameter body: (body) Input string as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -195,8 +193,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -210,7 +208,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ result: Result) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -243,8 +241,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -259,7 +257,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ result: Result) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -295,7 +293,7 @@ open class FakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -356,8 +354,8 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -385,7 +383,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ result: Result) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -420,7 +418,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -439,7 +437,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -527,8 +525,8 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -550,7 +548,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ result: Result) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -576,19 +574,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -613,8 +611,8 @@ open class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -634,7 +632,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ result: Result) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -658,13 +656,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -684,8 +682,8 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -699,8 +697,8 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the result */ - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ result: Result) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ result: Result) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -715,7 +713,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -734,8 +732,8 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -751,7 +749,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ result: Result) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -770,14 +768,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 3ee95e0d558..09c9696dec6 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,8 +7,6 @@ import Foundation - - open class FakeClassnameTags123API { /** To test class name in snake case @@ -16,7 +14,7 @@ open class FakeClassnameTags123API { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f6453d755eb..3c0ac53738a 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class PetAPI { /** Add a new pet to the store @@ -16,8 +14,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -32,7 +30,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ open class func addPet(body: Pet, completion: @escaping ((_ result: Result) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -69,8 +67,8 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -86,7 +84,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ result: Result) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -111,8 +109,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -139,7 +137,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(response?.body, error) } @@ -175,8 +173,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -193,7 +191,7 @@ open class PetAPI { - parameter tags: (query) Tags to filter by - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(response?.body, error) } @@ -229,8 +227,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -247,7 +245,7 @@ open class PetAPI { - parameter petId: (path) ID of pet to return - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -286,8 +284,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -301,8 +299,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -317,7 +315,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ open class func updatePet(body: Pet, completion: @escaping ((_ result: Result) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -355,8 +353,8 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -373,7 +371,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ result: Result) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -399,14 +397,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -422,7 +420,7 @@ open class PetAPI { - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(response?.body, error) } @@ -464,14 +462,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -487,7 +485,7 @@ open class PetAPI { - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in completion(response?.body, error) } @@ -529,14 +527,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 3540be19c3e..62ae519105c 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class StoreAPI { /** Delete purchase order by ID @@ -16,8 +14,8 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -32,7 +30,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the result */ open class func deleteOrder(orderId: String, completion: @escaping ((_ result: Result) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -54,8 +52,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -68,7 +66,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { + open class func getInventory(completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } @@ -78,7 +76,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the result */ - open class func getInventory(completion: @escaping ((_ result: Result<[String:Int], Error>) -> Void)) { + open class func getInventory(completion: @escaping ((_ result: Result<[String: Int], Error>) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in if let error = error { completion(.failure(error)) @@ -99,14 +97,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -117,7 +115,7 @@ open class StoreAPI { - parameter orderId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -153,8 +151,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -168,7 +166,7 @@ open class StoreAPI { - parameter body: (body) order placed for purchasing the pet - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 6ee23f9b678..c65cdfa1bce 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class UserAPI { /** Create user @@ -16,8 +14,8 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUser(body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -32,7 +30,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func createUser(body: User, completion: @escaping ((_ result: Result) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -66,8 +64,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -82,7 +80,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ result: Result) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -115,8 +113,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -131,7 +129,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func createUsersWithListInput(body: [User], completion: @escaping ((_ result: Result) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -164,8 +162,8 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -180,7 +178,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func deleteUser(username: String, completion: @escaping ((_ result: Result) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -202,8 +200,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -217,7 +215,7 @@ open class UserAPI { - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + open class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in completion(response?.body, error) } @@ -252,8 +250,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -268,7 +266,7 @@ open class UserAPI { - parameter password: (query) The password for login in clear text - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in completion(response?.body, error) } @@ -303,11 +301,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -321,8 +319,8 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + open class func logoutUser(completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -336,7 +334,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func logoutUser(completion: @escaping ((_ result: Result) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { @@ -353,8 +351,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -369,8 +367,8 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -386,7 +384,7 @@ open class UserAPI { - parameter completion: completion handler to receive the result */ open class func updateUser(username: String, body: User, completion: @escaping ((_ result: Result) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if let error = error { completion(.failure(error)) } else { diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index 57bab28b199..27cf29c6560 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ open class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 1f948ae12f7..74fcfcf2ad4 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 46d4828ceb6..5ed9f31e2a3 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 087b65ef044..7ab887f3113 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index bcd0a62e010..eb8f7e5e197 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ed63186cc45..492c1228008 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 74ec3850fb2..6db9b34d183 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 260526eb804..20bd6d103b3 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 06d5ac3c87b..43c4891e1e2 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index d38c8953f0f..a6e1b1d2e5e 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e943c40a8c4..af60a550bb1 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8277746be90..4dd8a9a9f5a 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b936721e454..bf0006e1a26 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d7bf3f5b13e..602a2a6d185 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index d71e55e3c19..79f271ed735 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift4/rxswiftLibrary/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/rxswiftLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/rxswiftLibrary/Package.swift b/samples/client/petstore/swift4/rxswiftLibrary/Package.swift index ad243b475b4..6c19a2b64cc 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/Package.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/Package.swift @@ -9,12 +9,12 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), - .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "4.5.0"), + .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "4.5.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -23,6 +23,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire", "RxSwift"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 172d3e1d6c1..819fc85beda 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class AnotherFakeAPI { /** To test special tags diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 9bebdd74425..edbc9b6fffc 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class FakeAPI { /** @@ -174,7 +172,7 @@ open class FakeAPI { */ open class func testBodyWithFileSchema(body: FileSchemaTestClass) -> Observable { return Observable.create { observer -> Disposable in - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -212,7 +210,7 @@ open class FakeAPI { */ open class func testBodyWithQueryParams(query: String, body: User) -> Observable { return Observable.create { observer -> Disposable in - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -307,7 +305,7 @@ open class FakeAPI { */ open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -345,7 +343,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -364,7 +362,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -454,7 +452,7 @@ open class FakeAPI { */ open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Observable { return Observable.create { observer -> Disposable in - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -483,19 +481,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -522,7 +520,7 @@ open class FakeAPI { */ open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> Observable { return Observable.create { observer -> Disposable in - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -549,13 +547,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -575,9 +573,9 @@ open class FakeAPI { - parameter param: (body) request body - returns: Observable */ - open class func testInlineAdditionalProperties(param: [String:String]) -> Observable { + open class func testInlineAdditionalProperties(param: [String: String]) -> Observable { return Observable.create { observer -> Disposable in - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -595,7 +593,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -616,7 +614,7 @@ open class FakeAPI { */ open class func testJsonFormData(param: String, param2: String) -> Observable { return Observable.create { observer -> Disposable in - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -638,14 +636,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 0129283fe4d..c34ace880ce 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class FakeClassnameTags123API { /** To test class name in snake case diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 556ebcef5e8..6b4797fc19a 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class PetAPI { /** Add a new pet to the store @@ -19,7 +17,7 @@ open class PetAPI { */ open class func addPet(body: Pet) -> Observable { return Observable.create { observer -> Disposable in - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -61,7 +59,7 @@ open class PetAPI { */ open class func deletePet(petId: Int64, apiKey: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -89,8 +87,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -146,8 +144,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -193,8 +191,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -243,8 +241,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -260,7 +258,7 @@ open class PetAPI { */ open class func updatePet(body: Pet) -> Observable { return Observable.create { observer -> Disposable in - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -303,7 +301,7 @@ open class PetAPI { */ open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -332,14 +330,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -388,14 +386,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -444,14 +442,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8c2b20948e..c03311277b9 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class StoreAPI { /** Delete purchase order by ID @@ -19,7 +17,7 @@ open class StoreAPI { */ open class func deleteOrder(orderId: String) -> Observable { return Observable.create { observer -> Disposable in - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -44,8 +42,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -58,7 +56,7 @@ open class StoreAPI { - returns: Observable<[String:Int]> */ - open class func getInventory() -> Observable<[String:Int]> { + open class func getInventory() -> Observable<[String: Int]> { return Observable.create { observer -> Disposable in getInventoryWithRequestBuilder().execute { (response, error) -> Void in if let error = error { @@ -83,14 +81,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -130,8 +128,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 2a877f7c7f0..ec28b4121d0 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -8,8 +8,6 @@ import Foundation import RxSwift - - open class UserAPI { /** Create user @@ -19,7 +17,7 @@ open class UserAPI { */ open class func createUser(body: User) -> Observable { return Observable.create { observer -> Disposable in - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -58,7 +56,7 @@ open class UserAPI { */ open class func createUsersWithArrayInput(body: [User]) -> Observable { return Observable.create { observer -> Disposable in - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -96,7 +94,7 @@ open class UserAPI { */ open class func createUsersWithListInput(body: [User]) -> Observable { return Observable.create { observer -> Disposable in - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -134,7 +132,7 @@ open class UserAPI { */ open class func deleteUser(username: String) -> Observable { return Observable.create { observer -> Disposable in - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -159,8 +157,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -202,8 +200,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -245,11 +243,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -265,7 +263,7 @@ open class UserAPI { */ open class func logoutUser() -> Observable { return Observable.create { observer -> Disposable in - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { @@ -285,8 +283,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -303,7 +301,7 @@ open class UserAPI { */ open class func updateUser(username: String, body: User) -> Observable { return Observable.create { observer -> Disposable in - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if let error = error { observer.onError(error) } else { diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index 57bab28b199..27cf29c6560 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ open class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 1f948ae12f7..74fcfcf2ad4 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 46d4828ceb6..5ed9f31e2a3 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 087b65ef044..7ab887f3113 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index bcd0a62e010..eb8f7e5e197 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ed63186cc45..492c1228008 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 74ec3850fb2..6db9b34d183 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 260526eb804..20bd6d103b3 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 06d5ac3c87b..43c4891e1e2 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index d38c8953f0f..a6e1b1d2e5e 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e943c40a8c4..af60a550bb1 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8277746be90..4dd8a9a9f5a 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b936721e454..bf0006e1a26 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d7bf3f5b13e..602a2a6d185 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index d71e55e3c19..79f271ed735 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/unwrapRequired/.openapi-generator/VERSION b/samples/client/petstore/swift4/unwrapRequired/.openapi-generator/VERSION index 58592f031f6..bfbf77eb7fa 100644 --- a/samples/client/petstore/swift4/unwrapRequired/.openapi-generator/VERSION +++ b/samples/client/petstore/swift4/unwrapRequired/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/unwrapRequired/Package.swift b/samples/client/petstore/swift4/unwrapRequired/Package.swift index a847bc5077d..e5c5f0f33b8 100644 --- a/samples/client/petstore/swift4/unwrapRequired/Package.swift +++ b/samples/client/petstore/swift4/unwrapRequired/Package.swift @@ -9,11 +9,11 @@ let package = Package( // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "PetstoreClient", - targets: ["PetstoreClient"]), + targets: ["PetstoreClient"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -22,6 +22,6 @@ let package = Package( name: "PetstoreClient", dependencies: ["Alamofire"], path: "PetstoreClient/Classes" - ), + ) ] ) diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index d94614b34fc..75dea243957 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -7,7 +7,7 @@ import Foundation public struct APIHelper { - public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { let destination = source.reduce(into: [String: Any]()) { (result, item) in if let value = item.value { result[item.key] = value @@ -20,17 +20,17 @@ public struct APIHelper { return destination } - public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in if let collection = item.value as? Array { - result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",") + result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } } } - public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { guard let source = source else { return nil } @@ -52,7 +52,7 @@ public struct APIHelper { return source } - public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in if let collection = item.value as? Array { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") @@ -68,4 +68,3 @@ public struct APIHelper { return destination } } - diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs.swift index 13586cdadd8..832282d224f 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -9,23 +9,23 @@ import Foundation open class PetstoreClientAPI { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? - public static var customHeaders: [String:String] = [:] + public static var customHeaders: [String: String] = [:] public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] - public let parameters: [String:Any]? + var headers: [String: String] + public let parameters: [String: Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. - public var onProgressReady: ((Progress) -> ())? + public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters @@ -35,7 +35,7 @@ open class RequestBuilder { addHeaders(PetstoreClientAPI.customHeaders) } - open func addHeaders(_ aHeaders:[String:String]) { + open func addHeaders(_ aHeaders: [String: String]) { for (header, value) in aHeaders { headers[header] = value } @@ -58,5 +58,5 @@ open class RequestBuilder { public protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type - func getBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1e6b7fc02c2..02e24286e3c 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class AnotherFakeAPI { /** To test special tags @@ -16,7 +14,7 @@ open class AnotherFakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 0bdeee0b2cb..b0b394aa06e 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,15 +7,13 @@ import Foundation - - open class FakeAPI { /** - parameter body: (body) Input boolean as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?,_ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -44,7 +42,7 @@ open class FakeAPI { - parameter body: (body) Input composite as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -73,7 +71,7 @@ open class FakeAPI { - parameter body: (body) Input number as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?,_ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -102,7 +100,7 @@ open class FakeAPI { - parameter body: (body) Input string as post body (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -131,8 +129,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -165,8 +163,8 @@ open class FakeAPI { - parameter body: (body) - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (response, error) -> Void in + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -202,7 +200,7 @@ open class FakeAPI { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } @@ -246,8 +244,8 @@ open class FakeAPI { - parameter callback: (form) None (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -282,7 +280,7 @@ open class FakeAPI { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -301,7 +299,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -389,8 +387,8 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (response, error) -> Void in + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -416,19 +414,19 @@ open class FakeAPI { open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -453,8 +451,8 @@ open class FakeAPI { - parameter int64Group: (query) Integer in group parameters (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (response, error) -> Void in + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -478,13 +476,13 @@ open class FakeAPI { open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON() ]) let nillableHeaders: [String: Any?] = [ @@ -504,8 +502,8 @@ open class FakeAPI { - parameter param: (body) request body - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String:String], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (response, error) -> Void in + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -520,7 +518,7 @@ open class FakeAPI { - parameter param: (body) request body - returns: RequestBuilder */ - open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String:String]) -> RequestBuilder { + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) @@ -539,8 +537,8 @@ open class FakeAPI { - parameter param2: (form) field2 - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (response, error) -> Void in + open class func testJsonFormData(param: String, param2: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -559,14 +557,14 @@ open class FakeAPI { open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 822a371cef3..060d434fbf2 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,8 +7,6 @@ import Foundation - - open class FakeClassnameTags123API { /** To test class name in snake case @@ -16,7 +14,7 @@ open class FakeClassnameTags123API { - parameter body: (body) client model - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index cc4397947d1..fe75962a72c 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class PetAPI { /** Add a new pet to the store @@ -16,8 +14,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func addPet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -54,8 +52,8 @@ open class PetAPI { - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -80,8 +78,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON() @@ -108,7 +106,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(response?.body, error) } @@ -127,8 +125,8 @@ open class PetAPI { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON() @@ -145,7 +143,7 @@ open class PetAPI { - parameter tags: (query) Tags to filter by - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(response?.body, error) } @@ -164,8 +162,8 @@ open class PetAPI { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON() @@ -182,7 +180,7 @@ open class PetAPI { - parameter petId: (path) ID of pet to return - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -204,8 +202,8 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -219,8 +217,8 @@ open class PetAPI { - parameter body: (body) Pet object that needs to be added to the store - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func updatePet(body: Pet, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -258,8 +256,8 @@ open class PetAPI { - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -285,14 +283,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -308,7 +306,7 @@ open class PetAPI { - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(response?.body, error) } @@ -331,14 +329,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -354,7 +352,7 @@ open class PetAPI { - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { (response, error) -> Void in completion(response?.body, error) } @@ -377,14 +375,14 @@ open class PetAPI { let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let formParams: [String:Any?] = [ + let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON() ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index b62f18f3f02..d5f627df52a 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class StoreAPI { /** Delete purchase order by ID @@ -16,8 +14,8 @@ open class StoreAPI { - parameter orderId: (path) ID of the order that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + open class func deleteOrder(orderId: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -39,8 +37,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -53,7 +51,7 @@ open class StoreAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(completion: @escaping ((_ data: [String:Int]?,_ error: Error?) -> Void)) { + open class func getInventory(completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } @@ -68,14 +66,14 @@ open class StoreAPI { - name: api_key - returns: RequestBuilder<[String:Int]> */ - open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) - let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } @@ -86,7 +84,7 @@ open class StoreAPI { - parameter orderId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } @@ -105,8 +103,8 @@ open class StoreAPI { let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -120,7 +118,7 @@ open class StoreAPI { - parameter body: (body) order placed for purchasing the pet - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(response?.body, error) } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 0e2d140e037..ef4f971a91e 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,6 @@ import Foundation - - open class UserAPI { /** Create user @@ -16,8 +14,8 @@ open class UserAPI { - parameter body: (body) Created user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUser(body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -51,8 +49,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -85,8 +83,8 @@ open class UserAPI { - parameter body: (body) List of user object - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -119,8 +117,8 @@ open class UserAPI { - parameter username: (path) The name that needs to be deleted - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + open class func deleteUser(username: String, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -142,8 +140,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -157,7 +155,7 @@ open class UserAPI { - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + open class func getUserByName(username: String, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in completion(response?.body, error) } @@ -175,8 +173,8 @@ open class UserAPI { let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() @@ -191,7 +189,7 @@ open class UserAPI { - parameter password: (query) The password for login in clear text - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in completion(response?.body, error) } @@ -208,11 +206,11 @@ open class UserAPI { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), + "username": username.encodeToJSON(), "password": password.encodeToJSON() ]) @@ -226,8 +224,8 @@ open class UserAPI { - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - logoutUserWithRequestBuilder().execute { (response, error) -> Void in + open class func logoutUser(completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (_, error) -> Void in if error == nil { completion((), error) } else { @@ -244,8 +242,8 @@ open class UserAPI { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path - let parameters: [String:Any]? = nil - + let parameters: [String: Any]? = nil + let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() @@ -260,8 +258,8 @@ open class UserAPI { - parameter body: (body) Updated user object - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?,_ error: Error?) -> Void)) { - updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + open class func updateUser(username: String, body: User, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (_, error) -> Void in if error == nil { completion((), error) } else { diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f8521a9c036..1d54e695608 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -12,7 +12,7 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { return AlamofireRequestBuilder.self } - func getBuilder() -> RequestBuilder.Type { + func getBuilder() -> RequestBuilder.Type { return AlamofireDecodableRequestBuilder.self } } @@ -50,7 +50,7 @@ private struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } @@ -88,17 +88,17 @@ open class AlamofireRequestBuilder: RequestBuilder { May be overridden by a subclass if you want to control the request configuration (e.g. to override the cache policy). */ - open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { - let managerId:String = UUID().uuidString + let managerId: String = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager - let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + let encoding: ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() let xMethod = Alamofire.HTTPMethod(rawValue: method) let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } @@ -111,8 +111,7 @@ open class AlamofireRequestBuilder: RequestBuilder { case let fileURL as URL: if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } - else { + } else { mpForm.append(fileURL, withName: k) } case let string as String: @@ -276,7 +275,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } - fileprivate func getFileName(fromContentDisposition contentDisposition : String?) -> String? { + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { guard let contentDisposition = contentDisposition else { return nil @@ -284,7 +283,7 @@ open class AlamofireRequestBuilder: RequestBuilder { let items = contentDisposition.components(separatedBy: ";") - var filename : String? = nil + var filename: String? for contentItem in items { @@ -295,7 +294,7 @@ open class AlamofireRequestBuilder: RequestBuilder { filename = contentItem return filename? - .replacingCharacters(in: range, with:"") + .replacingCharacters(in: range, with: "") .replacingOccurrences(of: "\"", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) } @@ -304,7 +303,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getPath(from url : URL) throws -> String { + fileprivate func getPath(from url: URL) throws -> String { guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { throw DownloadException.requestMissingPath @@ -318,7 +317,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } - fileprivate func getURL(from urlRequest : URLRequest) throws -> URL { + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { guard let url = urlRequest.url else { throw DownloadException.requestMissingURL @@ -329,7 +328,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } -fileprivate enum DownloadException : Error { +private enum DownloadException: Error { case responseDataMissing case responseFailed case requestMissing @@ -344,7 +343,7 @@ public enum AlamofireDecodableRequestBuilderError: Error { case generalError(Error) } -open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { if let credential = self.credential { @@ -436,7 +435,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilde return } - var responseObj: Response? = nil + var responseObj: Response? let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) if decodeResult.error == nil { diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift index 57bab28b199..27cf29c6560 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -47,9 +47,9 @@ open class CodableHelper { set { self.customJSONEncoder = newValue } } - open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { - var returnedDecodable: T? = nil - var returnedError: Error? = nil + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T: Decodable { + var returnedDecodable: T? + var returnedError: Error? do { returnedDecodable = try self.jsonDecoder.decode(type, from: data) @@ -60,9 +60,9 @@ open class CodableHelper { return (returnedDecodable, returnedError) } - open class func encode(_ value: T) -> EncodeResult where T : Encodable { + open class func encode(_ value: T) -> EncodeResult where T: Encodable { var returnedData: Data? - var returnedError: Error? = nil + var returnedError: Error? do { returnedData = try self.jsonEncoder.encode(value) @@ -72,4 +72,4 @@ open class CodableHelper { return (returnedData, returnedError) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 516590da5d9..e1ecb39726e 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,9 +7,9 @@ import Foundation open class Configuration { - + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" - -} \ No newline at end of file + +} diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 1f948ae12f7..74fcfcf2ad4 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -108,24 +108,24 @@ extension String: CodingKey { extension KeyedEncodingContainerProtocol { - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { var arrayContainer = nestedUnkeyedContainer(forKey: key) try arrayContainer.encode(contentsOf: values) } - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T : Encodable { + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { if let values = values { try encodeArray(values, forKey: key) } } - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T : Encodable { + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { for (key, value) in pairs { try encode(value, forKey: key) } } - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T : Encodable { + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { if let pairs = pairs { try encodeMap(pairs) } @@ -135,7 +135,7 @@ extension KeyedEncodingContainerProtocol { extension KeyedDecodingContainerProtocol { - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T : Decodable { + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { var tmpArray = [T]() var nestedContainer = try nestedUnkeyedContainer(forKey: key) @@ -147,8 +147,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T : Decodable { - var tmpArray: [T]? = nil + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? if contains(key) { tmpArray = try decodeArray(T.self, forKey: key) @@ -157,8 +157,8 @@ extension KeyedDecodingContainerProtocol { return tmpArray } - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T : Decodable { - var map: [Self.Key : T] = [:] + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] for key in allKeys { if !excludedKeys.contains(key) { @@ -171,5 +171,3 @@ extension KeyedDecodingContainerProtocol { } } - - diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift index ca05906d420..fb76bbed26f 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodableEncoding.swift @@ -42,7 +42,7 @@ public struct JSONDataEncoding: ParameterEncoding { } public static func encodingParameters(jsonData: Data?) -> Parameters? { - var returnedParams: Parameters? = nil + var returnedParams: Parameters? if let jsonData = jsonData, !jsonData.isEmpty { var params = Parameters() params[jsonDataKey] = jsonData diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift index 6ae673e1f8c..827bdec8778 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -10,8 +10,8 @@ import Alamofire open class JSONEncodingHelper { - open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { - var params: Parameters? = nil + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? // Encode the Encodable object if let encodableObj = encodableObj { @@ -25,7 +25,7 @@ open class JSONEncodingHelper { } open class func encodingParameters(forEncodableObject encodableObj: Any?) -> Parameters? { - var params: Parameters? = nil + var params: Parameters? if let encodableObj = encodableObj { do { @@ -39,5 +39,5 @@ open class JSONEncodingHelper { return params } - + } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models.swift index 40856389035..25161165865 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,7 +10,7 @@ protocol JSONEncodable { func encodeToJSON() -> Any } -public enum ErrorResponse : Error { +public enum ErrorResponse: Error { case error(Int, Data?, Error) } @@ -27,7 +27,7 @@ open class Response { public convenience init(response: HTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields - var header = [String:String]() + var header = [String: String]() for case let (key, value) as (String, String) in rawHeader { header[key] = value } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index e9c0e5a143d..83a06951ccd 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,18 +7,17 @@ import Foundation - public struct AdditionalPropertiesClass: Codable { - public var mapString: [String:String]? - public var mapMapString: [String:[String:String]]? + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? - public init(mapString: [String:String]?, mapMapString: [String:[String:String]]?) { + public init(mapString: [String: String]?, mapMapString: [String: [String: String]]?) { self.mapString = mapString self.mapMapString = mapMapString } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapString = "map_string" case mapMapString = "map_map_string" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 42696eb8043..88eceebd2a2 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,7 +7,6 @@ import Foundation - public struct Animal: Codable { public var className: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e7bea63f8ed..e09b0e9efdc 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -7,5 +7,4 @@ import Foundation - public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 781d0feae1b..ec270da8907 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,7 +7,6 @@ import Foundation - public struct ApiResponse: Codable { public var code: Int? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index ddf52a557ba..3843287630b 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -16,7 +15,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable { self.arrayArrayNumber = arrayArrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayArrayNumber = "ArrayArrayNumber" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index c5c237ef581..f8b198e81f5 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -16,7 +15,7 @@ public struct ArrayOfNumberOnly: Codable { self.arrayNumber = arrayNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c88a3a190ed..67f7f7e5151 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct ArrayTest: Codable { public var arrayOfString: [String]? @@ -20,7 +19,7 @@ public struct ArrayTest: Codable { self.arrayArrayOfModel = arrayArrayOfModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index b2487f3ebde..d576b50b1c9 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,6 @@ import Foundation - public struct Capitalization: Codable { public var smallCamel: String? @@ -27,7 +26,7 @@ public struct Capitalization: Codable { self.ATT_NAME = ATT_NAME } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case smallCamel case capitalCamel = "CapitalCamel" case smallSnake = "small_Snake" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 3ad15a0d07e..d6133a3dd5c 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,7 +7,6 @@ import Foundation - public struct Cat: Codable { public var className: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index b50c502feef..a51ad0dffab 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct CatAllOf: Codable { public var declawed: Bool? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 72732bfc0ae..48b43fc318d 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,7 +7,6 @@ import Foundation - public struct Category: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 8d2e2773825..00245ca3728 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,6 @@ import Foundation - public struct Client: Codable { public var client: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 2164955f52f..35c8cea0dd0 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,7 +7,6 @@ import Foundation - public struct Dog: Codable { public var className: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5b07a846597..7786f8acc5a 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,6 @@ import Foundation - public struct DogAllOf: Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 428c480ea51..5034ff0b8c6 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumArrays: Codable { public enum JustSymbol: String, Codable { @@ -26,7 +25,7 @@ public struct EnumArrays: Codable { self.arrayEnum = arrayEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justSymbol = "just_symbol" case arrayEnum = "array_enum" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 7280a621fec..3c1dfcac577 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -7,7 +7,6 @@ import Foundation - public enum EnumClass: String, Codable { case abc = "_abc" case efg = "-efg" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 724a0f6a315..b1eb8e98f89 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct EnumTest: Codable { public enum EnumString: String, Codable { @@ -42,7 +41,7 @@ public struct EnumTest: Codable { self.outerEnum = outerEnum } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case enumString = "enum_string" case enumStringRequired = "enum_string_required" case enumInteger = "enum_integer" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bc6db3d9d76..532f1457939 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,6 @@ import Foundation - public struct FileSchemaTestClass: Codable { public var file: File? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 125944b4661..4eed10b95a1 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,7 +7,6 @@ import Foundation - public struct FormatTest: Codable { public var integer: Int? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index c8ee22c8b10..906ddb06fb1 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct HasOnlyReadOnly: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fcf96a59c07..08d59953873 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,6 @@ import Foundation - public struct List: Codable { public var _123list: String? @@ -16,7 +15,7 @@ public struct List: Codable { self._123list = _123list } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _123list = "123-list" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 6807459a2aa..3a10a7dfcaf 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,26 +7,25 @@ import Foundation - public struct MapTest: Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" case lower = "lower" } - public var mapMapOfString: [String:[String:String]]? - public var mapOfEnumString: [String:String]? - public var directMap: [String:Bool]? + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? public var indirectMap: StringBooleanMap? - public init(mapMapOfString: [String:[String:String]]?, mapOfEnumString: [String:String]?, directMap: [String:Bool]?, indirectMap: StringBooleanMap?) { + public init(mapMapOfString: [String: [String: String]]?, mapOfEnumString: [String: String]?, directMap: [String: Bool]?, indirectMap: StringBooleanMap?) { self.mapMapOfString = mapMapOfString self.mapOfEnumString = mapOfEnumString self.directMap = directMap self.indirectMap = indirectMap } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" case directMap = "direct_map" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee0bc70f2c4..c3deb2f2893 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,14 +7,13 @@ import Foundation - public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { public var uuid: UUID? public var dateTime: Date? - public var map: [String:Animal]? + public var map: [String: Animal]? - public init(uuid: UUID?, dateTime: Date?, map: [String:Animal]?) { + public init(uuid: UUID?, dateTime: Date?, map: [String: Animal]?) { self.uuid = uuid self.dateTime = dateTime self.map = map diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 05b7e7231ca..78917d75b44 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -18,7 +18,7 @@ public struct Model200Response: Codable { self._class = _class } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case _class = "class" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index c6152e0b305..785c43bda4c 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -22,7 +22,7 @@ public struct Name: Codable { self._123number = _123number } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case name case snakeCase = "snake_case" case property diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index f61554861ab..abd2269e8e7 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,6 @@ import Foundation - public struct NumberOnly: Codable { public var justNumber: Double? @@ -16,7 +15,7 @@ public struct NumberOnly: Codable { self.justNumber = justNumber } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case justNumber = "JustNumber" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index d38c8953f0f..a6e1b1d2e5e 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,6 @@ import Foundation - public struct Order: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 5ef0caccc9f..49aec001c5d 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,7 +7,6 @@ import Foundation - public struct OuterComposite: Codable { public var myNumber: Double? @@ -20,7 +19,7 @@ public struct OuterComposite: Codable { self.myBoolean = myBoolean } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case myNumber = "my_number" case myString = "my_string" case myBoolean = "my_boolean" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index bd1643d279e..9f80fc95ecf 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -7,7 +7,6 @@ import Foundation - public enum OuterEnum: String, Codable { case placed = "placed" case approved = "approved" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 8ab1d6dc5eb..99eaa1329e4 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,6 @@ import Foundation - public struct Pet: Codable { public enum Status: String, Codable { diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index d0262dec8ce..0acd21fd100 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,6 @@ import Foundation - public struct ReadOnlyFirst: Codable { public var bar: String? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 18046e96933..b34ddc68142 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -16,7 +16,7 @@ public struct Return: Codable { self._return = _return } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case _return = "return" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c52be66ea64..e79fc45c0e9 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,7 +7,6 @@ import Foundation - public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -16,7 +15,7 @@ public struct SpecialModelName: Codable { self.specialPropertyName = specialPropertyName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case specialPropertyName = "$special[property.name]" } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffb79addebb..3f1237fee47 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,11 +7,9 @@ import Foundation - public struct StringBooleanMap: Codable { - - public var additionalProperties: [String:Bool] = [:] + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { get { @@ -44,5 +42,4 @@ public struct StringBooleanMap: Codable { additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8277746be90..4dd8a9a9f5a 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,7 +7,6 @@ import Foundation - public struct Tag: Codable { public var id: Int64? diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 86b39f910f8..07b590ab107 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderDefault: Codable { public var stringItem: String? = "what" @@ -24,7 +23,7 @@ public struct TypeHolderDefault: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index c16c6be2938..29d00516178 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,6 @@ import Foundation - public struct TypeHolderExample: Codable { public var stringItem: String? @@ -24,7 +23,7 @@ public struct TypeHolderExample: Codable { self.arrayItem = arrayItem } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/User.swift index d71e55e3c19..79f271ed735 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,7 +7,6 @@ import Foundation - public struct User: Codable { public var id: Int64? diff --git a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts index 36d9db6744e..1e305aa26e2 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/pet.service.ts @@ -208,7 +208,7 @@ export class PetService { * Add a new pet to the store * @param body Pet object that needs to be added to the store */ - public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -223,10 +223,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -262,7 +265,7 @@ export class PetService { * @param petId Pet id to delete * @param apiKey */ - public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -280,10 +283,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -308,7 +314,7 @@ export class PetService { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -328,12 +334,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -359,7 +368,7 @@ export class PetService { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -379,12 +388,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -410,7 +422,7 @@ export class PetService { * Returns a single pet * @param petId ID of pet to return */ - public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -422,12 +434,15 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -451,7 +466,7 @@ export class PetService { * Update an existing pet * @param body Pet object that needs to be added to the store */ - public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -466,10 +481,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -506,7 +524,7 @@ export class PetService { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -521,10 +539,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -577,7 +598,7 @@ export class PetService { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -592,11 +613,14 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts index 5a2292441dd..dd89404c1b8 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/store.service.ts @@ -121,17 +121,20 @@ export class StoreService { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -155,7 +158,7 @@ export class StoreService { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 @@ -164,11 +167,14 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -193,19 +199,22 @@ export class StoreService { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -229,19 +238,22 @@ export class StoreService { * Place an order for a pet * @param body order placed for purchasing the pet */ - public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts index 229426692fe..e7f2aed548a 100644 --- a/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/default/api/user.service.ts @@ -191,17 +191,20 @@ export class UserService { * This can only be done by the logged in user. * @param body Created user object */ - public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -234,17 +237,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -277,17 +283,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -321,17 +330,20 @@ export class UserService { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -355,19 +367,22 @@ export class UserService { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -392,7 +407,7 @@ export class UserService { * @param username The user name for login * @param password The password for login in clear text */ - public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -410,12 +425,15 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -439,14 +457,17 @@ export class UserService { /** * Logs out current logged in user session */ - public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -472,7 +493,7 @@ export class UserService { * @param username name that need to be deleted * @param body Updated user object */ - public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -482,10 +503,13 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts index 36d9db6744e..1e305aa26e2 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/pet.service.ts @@ -208,7 +208,7 @@ export class PetService { * Add a new pet to the store * @param body Pet object that needs to be added to the store */ - public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -223,10 +223,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -262,7 +265,7 @@ export class PetService { * @param petId Pet id to delete * @param apiKey */ - public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -280,10 +283,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -308,7 +314,7 @@ export class PetService { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -328,12 +334,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -359,7 +368,7 @@ export class PetService { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -379,12 +388,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -410,7 +422,7 @@ export class PetService { * Returns a single pet * @param petId ID of pet to return */ - public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -422,12 +434,15 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -451,7 +466,7 @@ export class PetService { * Update an existing pet * @param body Pet object that needs to be added to the store */ - public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -466,10 +481,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -506,7 +524,7 @@ export class PetService { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -521,10 +539,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -577,7 +598,7 @@ export class PetService { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -592,11 +613,14 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts index 5a2292441dd..dd89404c1b8 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/store.service.ts @@ -121,17 +121,20 @@ export class StoreService { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -155,7 +158,7 @@ export class StoreService { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 @@ -164,11 +167,14 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -193,19 +199,22 @@ export class StoreService { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -229,19 +238,22 @@ export class StoreService { * Place an order for a pet * @param body order placed for purchasing the pet */ - public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts index 229426692fe..e7f2aed548a 100644 --- a/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/npm/api/user.service.ts @@ -191,17 +191,20 @@ export class UserService { * This can only be done by the logged in user. * @param body Created user object */ - public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -234,17 +237,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -277,17 +283,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -321,17 +330,20 @@ export class UserService { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -355,19 +367,22 @@ export class UserService { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -392,7 +407,7 @@ export class UserService { * @param username The user name for login * @param password The password for login in clear text */ - public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -410,12 +425,15 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -439,14 +457,17 @@ export class UserService { /** * Logs out current logged in user session */ - public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -472,7 +493,7 @@ export class UserService { * @param username name that need to be deleted * @param body Updated user object */ - public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -482,10 +503,13 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts index ee64586f950..5225e2ceddc 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/pet.service.ts @@ -211,7 +211,7 @@ export class PetService implements PetServiceInterface { * Add a new pet to the store * @param body Pet object that needs to be added to the store */ - public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -226,10 +226,13 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -265,7 +268,7 @@ export class PetService implements PetServiceInterface { * @param petId Pet id to delete * @param apiKey */ - public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -283,10 +286,13 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -311,7 +317,7 @@ export class PetService implements PetServiceInterface { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -331,12 +337,15 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -362,7 +371,7 @@ export class PetService implements PetServiceInterface { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -382,12 +391,15 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -413,7 +425,7 @@ export class PetService implements PetServiceInterface { * Returns a single pet * @param petId ID of pet to return */ - public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -425,12 +437,15 @@ export class PetService implements PetServiceInterface { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -454,7 +469,7 @@ export class PetService implements PetServiceInterface { * Update an existing pet * @param body Pet object that needs to be added to the store */ - public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -469,10 +484,13 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -509,7 +527,7 @@ export class PetService implements PetServiceInterface { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -524,10 +542,13 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -580,7 +601,7 @@ export class PetService implements PetServiceInterface { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -595,11 +616,14 @@ export class PetService implements PetServiceInterface { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts index 6b2eee80069..b2b11558a35 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/store.service.ts @@ -124,17 +124,20 @@ export class StoreService implements StoreServiceInterface { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -158,7 +161,7 @@ export class StoreService implements StoreServiceInterface { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 @@ -167,11 +170,14 @@ export class StoreService implements StoreServiceInterface { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -196,19 +202,22 @@ export class StoreService implements StoreServiceInterface { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -232,19 +241,22 @@ export class StoreService implements StoreServiceInterface { * Place an order for a pet * @param body order placed for purchasing the pet */ - public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts index d999f296618..3b7effa5d28 100644 --- a/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v2/with-interfaces/api/user.service.ts @@ -194,17 +194,20 @@ export class UserService implements UserServiceInterface { * This can only be done by the logged in user. * @param body Created user object */ - public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -237,17 +240,20 @@ export class UserService implements UserServiceInterface { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -280,17 +286,20 @@ export class UserService implements UserServiceInterface { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -324,17 +333,20 @@ export class UserService implements UserServiceInterface { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -358,19 +370,22 @@ export class UserService implements UserServiceInterface { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -395,7 +410,7 @@ export class UserService implements UserServiceInterface { * @param username The user name for login * @param password The password for login in clear text */ - public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -413,12 +428,15 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -442,14 +460,17 @@ export class UserService implements UserServiceInterface { /** * Logs out current logged in user session */ - public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -475,7 +496,7 @@ export class UserService implements UserServiceInterface { * @param username name that need to be deleted * @param body Updated user object */ - public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -485,10 +506,13 @@ export class UserService implements UserServiceInterface { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts index 61b38e3aa07..575d13d4689 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/pet.service.ts @@ -67,10 +67,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -85,10 +85,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -128,10 +131,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -149,10 +152,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -181,10 +187,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -204,12 +210,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -239,10 +248,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -262,12 +271,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -297,10 +309,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -312,12 +324,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -345,10 +360,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -363,10 +378,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -407,10 +425,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -425,10 +443,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -481,10 +502,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -499,11 +520,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts index 7d46fee178f..e275f1bb4e3 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/store.service.ts @@ -54,20 +54,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -95,10 +98,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -107,11 +110,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -140,22 +146,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,22 +192,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts index 4ae84764be3..79bb71eab44 100644 --- a/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4.3/npm/api/user.service.ts @@ -54,20 +54,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -104,20 +107,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -154,20 +160,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -205,20 +214,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -246,22 +258,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -290,10 +305,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -311,12 +326,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -344,17 +362,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -384,10 +405,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -397,10 +418,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts index 36d9db6744e..1e305aa26e2 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/pet.service.ts @@ -208,7 +208,7 @@ export class PetService { * Add a new pet to the store * @param body Pet object that needs to be added to the store */ - public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -223,10 +223,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -262,7 +265,7 @@ export class PetService { * @param petId Pet id to delete * @param apiKey */ - public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -280,10 +283,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -308,7 +314,7 @@ export class PetService { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByStatusWithHttpInfo(status: Array<'available' | 'pending' | 'sold'>, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -328,12 +334,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -359,7 +368,7 @@ export class PetService { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -379,12 +388,15 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -410,7 +422,7 @@ export class PetService { * Returns a single pet * @param petId ID of pet to return */ - public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -422,12 +434,15 @@ export class PetService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -451,7 +466,7 @@ export class PetService { * Update an existing pet * @param body Pet object that needs to be added to the store */ - public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -466,10 +481,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -506,7 +524,7 @@ export class PetService { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -521,10 +539,13 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -577,7 +598,7 @@ export class PetService { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: Blob, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -592,11 +613,14 @@ export class PetService { headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts index 5a2292441dd..dd89404c1b8 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/store.service.ts @@ -121,17 +121,20 @@ export class StoreService { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -155,7 +158,7 @@ export class StoreService { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getInventoryWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 @@ -164,11 +167,14 @@ export class StoreService { headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -193,19 +199,22 @@ export class StoreService { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -229,19 +238,22 @@ export class StoreService { * Place an order for a pet * @param body order placed for purchasing the pet */ - public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts index 229426692fe..e7f2aed548a 100644 --- a/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v4/npm/api/user.service.ts @@ -191,17 +191,20 @@ export class UserService { * This can only be done by the logged in user. * @param body Created user object */ - public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUserWithHttpInfo(body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -234,17 +237,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -277,17 +283,20 @@ export class UserService { * Creates list of users with given input array * @param body List of user object */ - public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -321,17 +330,20 @@ export class UserService { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -355,19 +367,22 @@ export class UserService { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -392,7 +407,7 @@ export class UserService { * @param username The user name for login * @param password The password for login in clear text */ - public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -410,12 +425,15 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -439,14 +457,17 @@ export class UserService { /** * Logs out current logged in user session */ - public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable { + public logoutUserWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } @@ -472,7 +493,7 @@ export class UserService { * @param username name that need to be deleted * @param body Updated user object */ - public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs): Observable { + public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: RequestOptionsArgs, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -482,10 +503,13 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/pet.service.ts index f0b0cff753c..3baa93b09d4 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/pet.service.ts @@ -67,10 +67,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -85,10 +85,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -128,10 +131,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -149,10 +152,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -181,10 +187,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -204,12 +210,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -239,10 +248,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -262,12 +271,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -297,10 +309,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -312,12 +324,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -345,10 +360,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -363,10 +378,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -407,10 +425,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -425,10 +443,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -481,10 +502,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -499,11 +520,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/store.service.ts index 68737439b9a..9423bd8b423 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/store.service.ts @@ -54,20 +54,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -95,10 +98,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -107,11 +110,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -140,22 +146,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,22 +192,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/user.service.ts index cb25ca73c0f..0cefb7e9a47 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/api/user.service.ts @@ -54,20 +54,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -104,20 +107,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -154,20 +160,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -205,20 +214,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -246,22 +258,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -290,10 +305,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -311,12 +326,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -344,17 +362,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -384,10 +405,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -397,10 +418,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/pet.service.ts index f0b0cff753c..3baa93b09d4 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/pet.service.ts @@ -67,10 +67,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -85,10 +85,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -128,10 +131,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -149,10 +152,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -181,10 +187,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -204,12 +210,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -239,10 +248,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -262,12 +271,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -297,10 +309,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -312,12 +324,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -345,10 +360,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -363,10 +378,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -407,10 +425,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -425,10 +443,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -481,10 +502,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -499,11 +520,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/store.service.ts index 68737439b9a..9423bd8b423 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/store.service.ts @@ -54,20 +54,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -95,10 +98,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -107,11 +110,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -140,22 +146,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,22 +192,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/user.service.ts index cb25ca73c0f..0cefb7e9a47 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/api/user.service.ts @@ -54,20 +54,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -104,20 +107,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -154,20 +160,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -205,20 +214,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -246,22 +258,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -290,10 +305,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -311,12 +326,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -344,17 +362,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -384,10 +405,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -397,10 +418,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api.module.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/pet.service.ts index f0b0cff753c..3baa93b09d4 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/pet.service.ts @@ -67,10 +67,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -85,10 +85,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -128,10 +131,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -149,10 +152,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -181,10 +187,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -204,12 +210,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -239,10 +248,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -262,12 +271,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -297,10 +309,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -312,12 +324,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -345,10 +360,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -363,10 +378,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -407,10 +425,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -425,10 +443,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -481,10 +502,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -499,11 +520,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/store.service.ts index 68737439b9a..9423bd8b423 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/store.service.ts @@ -54,20 +54,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -95,10 +98,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -107,11 +110,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -140,22 +146,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,22 +192,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/user.service.ts index cb25ca73c0f..0cefb7e9a47 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/api/user.service.ts @@ -54,20 +54,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -104,20 +107,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -154,20 +160,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -205,20 +214,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -246,22 +258,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -290,10 +305,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -311,12 +326,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -344,17 +362,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -384,10 +405,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -397,10 +418,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/pet.service.ts index f0b0cff753c..3baa93b09d4 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/pet.service.ts @@ -67,10 +67,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -85,10 +85,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -128,10 +131,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -149,10 +152,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -181,10 +187,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -204,12 +210,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -239,10 +248,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -262,12 +271,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -297,10 +309,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -312,12 +324,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -345,10 +360,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -363,10 +378,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -407,10 +425,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -425,10 +443,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -481,10 +502,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -499,11 +520,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/store.service.ts index 68737439b9a..9423bd8b423 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/store.service.ts @@ -54,20 +54,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -95,10 +98,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -107,11 +110,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -140,22 +146,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,22 +192,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/user.service.ts index cb25ca73c0f..0cefb7e9a47 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/api/user.service.ts @@ -54,20 +54,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -104,20 +107,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -154,20 +160,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -205,20 +214,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -246,22 +258,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -290,10 +305,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -311,12 +326,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -344,17 +362,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -384,10 +405,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -397,10 +418,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api.module.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api.module.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api.module.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/pet.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/pet.service.ts index 1ab6514d615..beae55938b5 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/pet.service.ts @@ -106,10 +106,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(requestParameters: AddPetRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(requestParameters: AddPetRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(requestParameters: AddPetRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(requestParameters: AddPetRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(requestParameters: AddPetRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(requestParameters: AddPetRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(requestParameters: AddPetRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(requestParameters: AddPetRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); @@ -125,10 +125,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -167,10 +170,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(requestParameters: DeletePetRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(requestParameters: DeletePetRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(requestParameters: DeletePetRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(requestParameters: DeletePetRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(requestParameters: DeletePetRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(requestParameters: DeletePetRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(requestParameters: DeletePetRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(requestParameters: DeletePetRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const petId = requestParameters.petId; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); @@ -190,10 +193,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -222,10 +228,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(requestParameters: FindPetsByStatusRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const status = requestParameters.status; if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); @@ -246,12 +252,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -281,10 +290,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(requestParameters: FindPetsByTagsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const tags = requestParameters.tags; if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); @@ -305,12 +314,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -340,10 +352,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(requestParameters: GetPetByIdRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(requestParameters: GetPetByIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(requestParameters: GetPetByIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const petId = requestParameters.petId; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); @@ -356,12 +368,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -389,10 +404,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(requestParameters: UpdatePetRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(requestParameters: UpdatePetRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(requestParameters: UpdatePetRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); @@ -408,10 +423,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -450,10 +468,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(requestParameters: UpdatePetWithFormRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const petId = requestParameters.petId; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); @@ -471,10 +489,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -525,10 +546,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(requestParameters: UploadFileRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(requestParameters: UploadFileRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(requestParameters: UploadFileRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { const petId = requestParameters.petId; if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); @@ -546,11 +567,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/store.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/store.service.ts index 624eed3ea74..fd0cff4bc09 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/store.service.ts @@ -68,10 +68,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(requestParameters: DeleteOrderRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(requestParameters: DeleteOrderRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(requestParameters: DeleteOrderRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const orderId = requestParameters.orderId; if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); @@ -79,10 +79,13 @@ export class StoreService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -110,10 +113,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -122,11 +125,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -155,10 +161,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(requestParameters: GetOrderByIdRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(requestParameters: GetOrderByIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(requestParameters: GetOrderByIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const orderId = requestParameters.orderId; if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); @@ -166,12 +172,15 @@ export class StoreService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -199,10 +208,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(requestParameters: PlaceOrderRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(requestParameters: PlaceOrderRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(requestParameters: PlaceOrderRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); @@ -210,12 +219,15 @@ export class StoreService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/user.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/user.service.ts index 02f139bd64a..44e12277eb7 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/api/user.service.ts @@ -86,10 +86,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(requestParameters: CreateUserRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(requestParameters: CreateUserRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(requestParameters: CreateUserRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(requestParameters: CreateUserRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(requestParameters: CreateUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(requestParameters: CreateUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(requestParameters: CreateUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(requestParameters: CreateUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); @@ -97,10 +97,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -137,10 +140,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); @@ -148,10 +151,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -188,10 +194,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(requestParameters: CreateUsersWithListInputRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const body = requestParameters.body; if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); @@ -199,10 +205,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -240,10 +249,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(requestParameters: DeleteUserRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(requestParameters: DeleteUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(requestParameters: DeleteUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const username = requestParameters.username; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); @@ -251,10 +260,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -282,10 +294,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(requestParameters: GetUserByNameRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(requestParameters: GetUserByNameRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(requestParameters: GetUserByNameRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const username = requestParameters.username; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); @@ -293,12 +305,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -326,10 +341,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(requestParameters: LoginUserRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(requestParameters: LoginUserRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(requestParameters: LoginUserRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(requestParameters: LoginUserRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(requestParameters: LoginUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(requestParameters: LoginUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(requestParameters: LoginUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(requestParameters: LoginUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { const username = requestParameters.username; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); @@ -349,12 +364,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -382,17 +400,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -421,10 +442,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(requestParameters: UpdateUserRequestParams, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(requestParameters: UpdateUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(requestParameters: UpdateUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { const username = requestParameters.username; if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); @@ -436,10 +457,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api.module.ts index 8487243a83b..5e6ebe12ae0 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api.module.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class ApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api.module.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api.module.ts index 62e18a783d3..57092b10bb0 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api.module.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api.module.ts @@ -11,10 +11,7 @@ import { UserService } from './api/user.service'; imports: [], declarations: [], exports: [], - providers: [ - PetService, - StoreService, - UserService ] + providers: [] }) export class PetStoreApiModule { public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/pet.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/pet.service.ts index 110615d2f42..752adbf45c7 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/pet.service.ts @@ -69,10 +69,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public addPet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } @@ -87,10 +87,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -130,10 +133,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean): Observable; - public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } @@ -151,10 +154,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -183,10 +189,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } @@ -206,12 +212,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -241,10 +250,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean): Observable>; - public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean): Observable>>; - public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } @@ -264,12 +273,15 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -299,10 +311,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getPetById(petId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getPetById(petId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } @@ -314,12 +326,15 @@ export class PetService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -347,10 +362,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable; - public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } @@ -365,10 +380,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -409,10 +427,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean): Observable; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean): Observable>; - public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } @@ -427,10 +445,13 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -483,10 +504,10 @@ export class PetService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean): Observable; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean): Observable>; - public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false ): Observable { + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } @@ -501,11 +522,14 @@ export class PetService { headers = headers.set('Authorization', 'Bearer ' + accessToken); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/store.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/store.service.ts index 0bacbf87c22..478959481a9 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/store.service.ts @@ -56,20 +56,23 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -97,10 +100,10 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getInventory(observe?: 'body', reportProgress?: boolean): Observable<{ [key: string]: number; }>; - public getInventory(observe?: 'response', reportProgress?: boolean): Observable>; - public getInventory(observe?: 'events', reportProgress?: boolean): Observable>; - public getInventory(observe: any = 'body', reportProgress: boolean = false ): Observable { + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { let headers = this.defaultHeaders; @@ -109,11 +112,14 @@ export class StoreService { headers = headers.set('api_key', this.configuration.apiKeys["api_key"]); } - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -142,22 +148,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean): Observable; - public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean): Observable>; - public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -185,22 +194,25 @@ export class StoreService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean): Observable; - public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean): Observable>; - public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false ): Observable { + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/user.service.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/user.service.ts index d344374967d..6240c41d44a 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/api/user.service.ts @@ -56,20 +56,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, observe?: 'body', reportProgress?: boolean): Observable; - public createUser(body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public createUser(body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public createUser(body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -106,20 +109,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -156,20 +162,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean): Observable; - public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean): Observable>; - public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false ): Observable { + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -207,20 +216,23 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public deleteUser(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public deleteUser(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -248,22 +260,25 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public getUserByName(username: string, observe?: 'body', reportProgress?: boolean): Observable; - public getUserByName(username: string, observe?: 'response', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe?: 'events', reportProgress?: boolean): Observable>; - public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -292,10 +307,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean): Observable; - public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean): Observable>; - public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false ): Observable { + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json'}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } @@ -313,12 +328,15 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - 'application/xml', - 'application/json' - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -346,17 +364,20 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public logoutUser(observe?: 'body', reportProgress?: boolean): Observable; - public logoutUser(observe?: 'response', reportProgress?: boolean): Observable>; - public logoutUser(observe?: 'events', reportProgress?: boolean): Observable>; - public logoutUser(observe: any = 'body', reportProgress: boolean = false ): Observable { + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } @@ -386,10 +407,10 @@ export class UserService { * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ - public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean): Observable; - public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean): Observable>; - public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false ): Observable { + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } @@ -399,10 +420,13 @@ export class UserService { let headers = this.defaultHeaders; - // to determine the Accept header - const httpHeaderAccepts: string[] = [ - ]; - const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } diff --git a/samples/client/test/swift4/default/.openapi-generator/VERSION b/samples/client/test/swift4/default/.openapi-generator/VERSION index e4955748d3e..58592f031f6 100644 --- a/samples/client/test/swift4/default/.openapi-generator/VERSION +++ b/samples/client/test/swift4/default/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.2-SNAPSHOT \ No newline at end of file +4.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift index 74fcfcf2ad4..93579843a9d 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift @@ -80,6 +80,12 @@ extension URL: JSONEncodable { } } +extension URL: JSONEncodable { + func encodeToJSON() -> Any { + return self + } +} + extension UUID: JSONEncodable { func encodeToJSON() -> Any { return self.uuidString diff --git a/samples/documentation/markdown/.openapi-generator-ignore b/samples/documentation/markdown/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/documentation/markdown/.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/documentation/markdown/.openapi-generator/VERSION b/samples/documentation/markdown/.openapi-generator/VERSION new file mode 100644 index 00000000000..58592f031f6 --- /dev/null +++ b/samples/documentation/markdown/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/documentation/markdown/Apis/PetApi.md b/samples/documentation/markdown/Apis/PetApi.md new file mode 100644 index 00000000000..aef17fbd12f --- /dev/null +++ b/samples/documentation/markdown/Apis/PetApi.md @@ -0,0 +1,227 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](/Models/Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | [default to null] + **apiKey** | **String**| | [optional] [default to null] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **findPetsByStatus** +> List findPetsByStatus(status) + +Finds Pets by status + + Multiple status values can be provided with comma separated strings + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List**](/Models/String.md)| Status values that need to be considered for filter | [default to null] [enum: available, pending, sold] + +### Return type + +[**List**](/Models/Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List findPetsByTags(tags) + +Finds Pets by tags + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List**](/Models/String.md)| Tags to filter by | [default to null] + +### Return type + +[**List**](/Models/Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + + Returns a single pet + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | [default to null] + +### Return type + +[**Pet**](/Models/Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](/Models/Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | [default to null] + **name** | **String**| Updated name of the pet | [optional] [default to null] + **status** | **String**| Updated status of the pet | [optional] [default to null] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +# **uploadFile** +> ApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | [default to null] + **additionalMetadata** | **String**| Additional data to pass to server | [optional] [default to null] + **file** | **File**| file to upload | [optional] [default to null] + +### Return type + +[**ApiResponse**](/Models/ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + diff --git a/samples/documentation/markdown/Apis/StoreApi.md b/samples/documentation/markdown/Apis/StoreApi.md new file mode 100644 index 00000000000..9b7ce9f21f0 --- /dev/null +++ b/samples/documentation/markdown/Apis/StoreApi.md @@ -0,0 +1,115 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | [default to null] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **getInventory** +> Map getInventory() + +Returns pet inventories by status + + Returns a map of status codes to quantities + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map**](/Models/integer.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | [default to null] + +### Return type + +[**Order**](/Models/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](/Models/Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](/Models/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + diff --git a/samples/documentation/markdown/Apis/UserApi.md b/samples/documentation/markdown/Apis/UserApi.md new file mode 100644 index 00000000000..f92b65c3344 --- /dev/null +++ b/samples/documentation/markdown/Apis/UserApi.md @@ -0,0 +1,221 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + + This can only be done by the logged in user. + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](/Models/User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](/Models/User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](/Models/User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + + This can only be done by the logged in user. + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | [default to null] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | [default to null] + +### Return type + +[**User**](/Models/User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [default to null] + **password** | **String**| The password for login in clear text | [default to null] + +### Return type + +[**String**](/Models/string.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + + This can only be done by the logged in user. + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | [default to null] + **body** | [**User**](/Models/User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + diff --git a/samples/documentation/markdown/Models/ApiResponse.md b/samples/documentation/markdown/Models/ApiResponse.md new file mode 100644 index 00000000000..1fc3546ce76 --- /dev/null +++ b/samples/documentation/markdown/Models/ApiResponse.md @@ -0,0 +1,11 @@ +# ./Models.ApiResponse +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | [**Integer**](integer.md) | | [optional] [default to null] +**type** | [**String**](string.md) | | [optional] [default to null] +**message** | [**String**](string.md) | | [optional] [default to null] + +[[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/documentation/markdown/Models/Category.md b/samples/documentation/markdown/Models/Category.md new file mode 100644 index 00000000000..7dfffafdfc6 --- /dev/null +++ b/samples/documentation/markdown/Models/Category.md @@ -0,0 +1,10 @@ +# ./Models.Category +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | [**Long**](long.md) | | [optional] [default to null] +**name** | [**String**](string.md) | | [optional] [default to null] + +[[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/documentation/markdown/Models/Order.md b/samples/documentation/markdown/Models/Order.md new file mode 100644 index 00000000000..1b982b995ea --- /dev/null +++ b/samples/documentation/markdown/Models/Order.md @@ -0,0 +1,14 @@ +# ./Models.Order +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | [**Long**](long.md) | | [optional] [default to null] +**petId** | [**Long**](long.md) | | [optional] [default to null] +**quantity** | [**Integer**](integer.md) | | [optional] [default to null] +**shipDate** | [**Date**](DateTime.md) | | [optional] [default to null] +**status** | [**String**](string.md) | Order Status | [optional] [default to null] +**complete** | [**Boolean**](boolean.md) | | [optional] [default to false] + +[[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/documentation/markdown/Models/Pet.md b/samples/documentation/markdown/Models/Pet.md new file mode 100644 index 00000000000..88378fd5169 --- /dev/null +++ b/samples/documentation/markdown/Models/Pet.md @@ -0,0 +1,14 @@ +# ./Models.Pet +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | [**Long**](long.md) | | [optional] [default to null] +**category** | [**Category**](Category.md) | | [optional] [default to null] +**name** | [**String**](string.md) | | [default to null] +**photoUrls** | [**List**](string.md) | | [default to null] +**tags** | [**List**](Tag.md) | | [optional] [default to null] +**status** | [**String**](string.md) | pet status in the store | [optional] [default to null] + +[[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/documentation/markdown/Models/Tag.md b/samples/documentation/markdown/Models/Tag.md new file mode 100644 index 00000000000..d13aa870a5a --- /dev/null +++ b/samples/documentation/markdown/Models/Tag.md @@ -0,0 +1,10 @@ +# ./Models.Tag +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | [**Long**](long.md) | | [optional] [default to null] +**name** | [**String**](string.md) | | [optional] [default to null] + +[[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/documentation/markdown/Models/User.md b/samples/documentation/markdown/Models/User.md new file mode 100644 index 00000000000..5af4e8e1724 --- /dev/null +++ b/samples/documentation/markdown/Models/User.md @@ -0,0 +1,16 @@ +# ./Models.User +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | [**Long**](long.md) | | [optional] [default to null] +**username** | [**String**](string.md) | | [optional] [default to null] +**firstName** | [**String**](string.md) | | [optional] [default to null] +**lastName** | [**String**](string.md) | | [optional] [default to null] +**email** | [**String**](string.md) | | [optional] [default to null] +**password** | [**String**](string.md) | | [optional] [default to null] +**phone** | [**String**](string.md) | | [optional] [default to null] +**userStatus** | [**Integer**](integer.md) | User Status | [optional] [default to null] + +[[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/documentation/markdown/README.md b/samples/documentation/markdown/README.md new file mode 100644 index 00000000000..2e0854ed92a --- /dev/null +++ b/samples/documentation/markdown/README.md @@ -0,0 +1,62 @@ +# Documentation for OpenAPI Petstore + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](Apis/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](Apis/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](Apis/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](Apis/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](Apis/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](Apis/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](Apis/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](Apis/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](Apis/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](Apis/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](Apis/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](Apis/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](Apis/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](Apis/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](Apis/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](Apis/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](Apis/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](Apis/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](Apis/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](Apis/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [/Models.ApiResponse](Models/ApiResponse.md) + - [/Models.Category](Models/Category.md) + - [/Models.Order](Models/Order.md) + - [/Models.Pet](Models/Pet.md) + - [/Models.Tag](Models/Tag.md) + - [/Models.User](Models/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md index f78b00bdb81..d030bad9835 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md @@ -26,6 +26,47 @@ Put the package under your project folder and add the following in import: import sw "./openapi" ``` +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + ## Documentation for API Endpoints All URIs are relative to *http://petstore.swagger.io:80/v2* diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go index acc143f53a3..70a24791ad2 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go @@ -41,8 +41,12 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, cli localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/another-fake/dummy" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "AnotherFakeApiService.Call123TestSpecialTags") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/another-fake/dummy" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_default.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_default.go index 6dfb9613dfa..dd977e26c03 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_default.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_default.go @@ -39,8 +39,12 @@ func (a *DefaultApiService) FooGet(ctx _context.Context) (InlineResponseDefault, localVarReturnValue InlineResponseDefault ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/foo" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "DefaultApiService.FooGet") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/foo" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go index 53964c30b0d..7f38a455470 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go @@ -42,8 +42,12 @@ func (a *FakeApiService) FakeHealthGet(ctx _context.Context) (HealthCheckResult, localVarReturnValue HealthCheckResult ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/health" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeHealthGet") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/health" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -134,8 +138,12 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa localVarReturnValue bool ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/boolean" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterBooleanSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/boolean" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -231,8 +239,12 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local localVarReturnValue OuterComposite ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/composite" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterCompositeSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/composite" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -332,8 +344,12 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar localVarReturnValue float32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/number" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterNumberSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/number" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -429,8 +445,12 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar localVarReturnValue string ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/outer/string" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.FakeOuterStringSerialize") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/outer/string" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -518,8 +538,12 @@ func (a *FakeApiService) TestBodyWithFileSchema(ctx _context.Context, fileSchema localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/body-with-file-schema" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithFileSchema") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/body-with-file-schema" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -586,8 +610,12 @@ func (a *FakeApiService) TestBodyWithQueryParams(ctx _context.Context, query str localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/body-with-query-params" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestBodyWithQueryParams") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/body-with-query-params" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -657,8 +685,12 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, client Client) (C localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestClientModel") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -771,8 +803,12 @@ func (a *FakeApiService) TestEndpointParameters(ctx _context.Context, number flo localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEndpointParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -915,8 +951,12 @@ func (a *FakeApiService) TestEnumParameters(ctx _context.Context, localVarOption localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestEnumParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -1026,8 +1066,12 @@ func (a *FakeApiService) TestGroupParameters(ctx _context.Context, requiredStrin localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestGroupParameters") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -1103,8 +1147,12 @@ func (a *FakeApiService) TestInlineAdditionalProperties(ctx _context.Context, re localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/inline-additionalProperties" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestInlineAdditionalProperties") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/inline-additionalProperties" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -1171,8 +1219,12 @@ func (a *FakeApiService) TestJsonFormData(ctx _context.Context, param string, pa localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/jsonFormData" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestJsonFormData") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/jsonFormData" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -1243,8 +1295,12 @@ func (a *FakeApiService) TestQueryParameterCollectionFormat(ctx _context.Context localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/test-query-paramters" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeApiService.TestQueryParameterCollectionFormat") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/test-query-paramters" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index e64fa111ce7..a85385b85fd 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -41,8 +41,12 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, cli localVarReturnValue Client ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake_classname_test" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "FakeClassnameTags123ApiService.TestClassname") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake_classname_test" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go index a96faf2bac8..e52c8158f5c 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go @@ -14,7 +14,6 @@ import ( _ioutil "io/ioutil" _nethttp "net/http" _neturl "net/url" - "fmt" "strings" "github.com/antihax/optional" "os" @@ -42,8 +41,12 @@ func (a *PetApiService) AddPet(ctx _context.Context, pet Pet) (*_nethttp.Respons localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.AddPet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -116,9 +119,13 @@ func (a *PetApiService) DeletePet(ctx _context.Context, petId int64, localVarOpt localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" - localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.DeletePet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -188,8 +195,12 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) localVarReturnValue []Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/findByStatus" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByStatus") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/findByStatus" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -243,7 +254,6 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -277,8 +287,12 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P localVarReturnValue []Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/findByTags" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.FindPetsByTags") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/findByTags" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -332,7 +346,6 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -366,9 +379,13 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne localVarReturnValue Pet ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" - localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.GetPetById") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -435,7 +452,6 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -466,8 +482,12 @@ func (a *PetApiService) UpdatePet(ctx _context.Context, pet Pet) (*_nethttp.Resp localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePet") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -542,9 +562,13 @@ func (a *PetApiService) UpdatePetWithForm(ctx _context.Context, petId int64, loc localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}" - localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UpdatePetWithForm") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -625,9 +649,13 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp localVarReturnValue ApiResponse ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/pet/{petId}/uploadImage" - localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFile") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet/{petId}/uploadImage" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -737,9 +765,13 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i localVarReturnValue ApiResponse ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/fake/{petId}/uploadImageWithRequiredFile" - localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", petId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "PetApiService.UploadFileWithRequiredFile") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/{petId}/uploadImageWithRequiredFile" + localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", _neturl.QueryEscape(parameterToString(petId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go index 826647ff744..f1162bb61c3 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go @@ -14,7 +14,6 @@ import ( _ioutil "io/ioutil" _nethttp "net/http" _neturl "net/url" - "fmt" "strings" ) @@ -41,9 +40,13 @@ func (a *StoreApiService) DeleteOrder(ctx _context.Context, orderId string) (*_n localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}" - localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", orderId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.DeleteOrder") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order/{order_id}" + localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -109,8 +112,12 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32, localVarReturnValue map[string]int32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/inventory" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetInventory") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/inventory" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -209,9 +216,13 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord localVarReturnValue Order ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order/{order_id}" - localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", orderId)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.GetOrderById") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order/{order_id}" + localVarPath = strings.Replace(localVarPath, "{"+"order_id"+"}", _neturl.QueryEscape(parameterToString(orderId, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -270,7 +281,6 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -303,8 +313,12 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, order Order) (Order, localVarReturnValue Order ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/store/order" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "StoreApiService.PlaceOrder") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/store/order" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -359,7 +373,6 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, order Order) (Order, } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go index a5510a407d5..3d3d76f52a9 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go @@ -14,7 +14,6 @@ import ( _ioutil "io/ioutil" _nethttp "net/http" _neturl "net/url" - "fmt" "strings" ) @@ -41,8 +40,12 @@ func (a *UserApiService) CreateUser(ctx _context.Context, user User) (*_nethttp. localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -108,8 +111,12 @@ func (a *UserApiService) CreateUsersWithArrayInput(ctx _context.Context, user [] localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/createWithArray" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithArrayInput") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/createWithArray" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -175,8 +182,12 @@ func (a *UserApiService) CreateUsersWithListInput(ctx _context.Context, user []U localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/createWithList" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.CreateUsersWithListInput") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/createWithList" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -243,9 +254,13 @@ func (a *UserApiService) DeleteUser(ctx _context.Context, username string) (*_ne localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" - localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.DeleteUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -311,9 +326,13 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U localVarReturnValue User ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" - localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.GetUserByName") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -366,7 +385,6 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -400,8 +418,12 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo localVarReturnValue string ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/login" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LoginUser") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/login" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -456,7 +478,6 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr - return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -486,8 +507,12 @@ func (a *UserApiService) LogoutUser(ctx _context.Context) (*_nethttp.Response, e localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/logout" + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.LogoutUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/logout" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} @@ -553,9 +578,13 @@ func (a *UserApiService) UpdateUser(ctx _context.Context, username string, user localVarFileBytes []byte ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/user/{username}" - localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", username)), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(ctx, "UserApiService.UpdateUser") + if err != nil { + return nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/user/{username}" + localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", _neturl.QueryEscape(parameterToString(username, "")) , -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/client.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/client.go index d531341577f..6b2ddc386d5 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/client.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/client.go @@ -200,11 +200,6 @@ func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return resp, err } -// ChangeBasePath changes base path to allow switching to mocks -func (c *APIClient) ChangeBasePath(path string) { - c.cfg.BasePath = path -} - // Allow modification of underlying config for alternate implementations and testing // Caution: modifying the configuration while live can cause data races and potentially unwanted behavior func (c *APIClient) GetConfig() *Configuration { diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/configuration.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/configuration.go index 04cac069b34..4716060a6b0 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/configuration.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/configuration.go @@ -10,6 +10,7 @@ package openapi import ( + "context" "fmt" "net/http" "strings" @@ -37,6 +38,18 @@ var ( // ContextAPIKeys takes a string apikey as authentication for the request ContextAPIKeys = contextKey("apiKeys") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth @@ -60,32 +73,35 @@ type ServerVariable struct { // ServerConfiguration stores the information about a server type ServerConfiguration struct { - Url string + URL string Description string Variables map[string]ServerVariable } +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + // Configuration stores the configuration of the API client type Configuration struct { - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - Debug bool `json:"debug,omitempty"` - Servers []ServerConfiguration - HTTPClient *http.Client + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client } // NewConfiguration returns a new Configuration object func NewConfiguration() *Configuration { cfg := &Configuration{ - BasePath: "http://petstore.swagger.io:80/v2", - DefaultHeader: make(map[string]string), - UserAgent: "OpenAPI-Generator/1.0.0/go", - Debug: false, - Servers: []ServerConfiguration{{ - Url: "http://{server}.swagger.io:{port}/v2", + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://{server}.swagger.io:{port}/v2", Description: "petstore server", Variables: map[string]ServerVariable{ "server": ServerVariable{ @@ -107,7 +123,8 @@ func NewConfiguration() *Configuration { }, }, }, - Url: "https://localhost:8080/{version}", + { + URL: "https://localhost:8080/{version}", Description: "The local server", Variables: map[string]ServerVariable{ "version": ServerVariable{ @@ -121,6 +138,28 @@ func NewConfiguration() *Configuration { }, }, }, + OperationServers: map[string]ServerConfigurations{ + "PetApiService.AddPet": { + { + URL: "http://petstore.swagger.io/v2", + Description: "No description provided", + }, + { + URL: "http://path-server-test.petstore.local/v2", + Description: "No description provided", + }, + }, + "PetApiService.UpdatePet": { + { + URL: "http://petstore.swagger.io/v2", + Description: "No description provided", + }, + { + URL: "http://path-server-test.petstore.local/v2", + Description: "No description provided", + }, + }, + }, } return cfg } @@ -130,13 +169,13 @@ func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } -// ServerUrl returns URL based on server settings -func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) { - if index < 0 || len(c.Servers) <= index { - return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1) +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) } - server := c.Servers[index] - url := server.Url + server := sc[index] + url := server.URL // go through variables and replace placeholders for name, variable := range server.Variables { @@ -157,3 +196,84 @@ func (c *Configuration) ServerUrl(index int, variables map[string]string) (strin } return url, nil } + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_200_response.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_200_response.go index f578c71ae1d..f746eb97c50 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_200_response.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_200_response.go @@ -97,7 +97,7 @@ func (v NullableModel200Response) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableModel200Response) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableModel200Response) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model__special_model_name_.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model__special_model_name_.go index e8e5786195d..a327da2f86f 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model__special_model_name_.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model__special_model_name_.go @@ -63,7 +63,7 @@ func (v NullableSpecialModelName) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableSpecialModelName) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableSpecialModelName) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go index ea7b0eb7d77..2448275032b 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_additional_properties_class.go @@ -97,7 +97,7 @@ func (v NullableAdditionalPropertiesClass) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_animal.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_animal.go index 1bca9d7f269..bec70d7337a 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_animal.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_animal.go @@ -79,7 +79,7 @@ func (v NullableAnimal) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableAnimal) UnmarshalJSON(src []byte) error { @@ -90,4 +90,3 @@ func (v *NullableAnimal) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_api_response.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_api_response.go index 24e67257987..94b4983c8b3 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_api_response.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_api_response.go @@ -131,7 +131,7 @@ func (v NullableApiResponse) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableApiResponse) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableApiResponse) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go index d3a9679bf03..02cbaaae246 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_array_of_number_only.go @@ -63,7 +63,7 @@ func (v NullableArrayOfArrayOfNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayOfArrayOfNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableArrayOfArrayOfNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go index 34dfd56be88..dca9e7022ab 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_of_number_only.go @@ -63,7 +63,7 @@ func (v NullableArrayOfNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayOfNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableArrayOfNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_test_.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_test_.go index 959ec1702db..b4566967aaf 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_test_.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_array_test_.go @@ -131,7 +131,7 @@ func (v NullableArrayTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableArrayTest) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableArrayTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_capitalization.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_capitalization.go index 9fa45b1b216..a4489cc259c 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_capitalization.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_capitalization.go @@ -234,7 +234,7 @@ func (v NullableCapitalization) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCapitalization) UnmarshalJSON(src []byte) error { @@ -245,4 +245,3 @@ func (v *NullableCapitalization) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat.go index 8c79d36766a..952bf040204 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat.go @@ -113,7 +113,7 @@ func (v NullableCat) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCat) UnmarshalJSON(src []byte) error { @@ -124,4 +124,3 @@ func (v *NullableCat) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat_all_of.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat_all_of.go index af2e351aa80..53da305ec11 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat_all_of.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_cat_all_of.go @@ -63,7 +63,7 @@ func (v NullableCatAllOf) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCatAllOf) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableCatAllOf) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_category.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_category.go index b4e6f0fecd8..f942863971d 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_category.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_category.go @@ -79,7 +79,7 @@ func (v NullableCategory) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableCategory) UnmarshalJSON(src []byte) error { @@ -90,4 +90,3 @@ func (v *NullableCategory) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_class_model.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_class_model.go index a4d8428053a..9ac228a5eba 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_class_model.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_class_model.go @@ -63,7 +63,7 @@ func (v NullableClassModel) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableClassModel) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableClassModel) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_client.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_client.go index b564954b90e..5d959e49a77 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_client.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_client.go @@ -63,7 +63,7 @@ func (v NullableClient) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableClient) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableClient) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog.go index 71c6cf17e2c..9cf3882d97c 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog.go @@ -113,7 +113,7 @@ func (v NullableDog) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableDog) UnmarshalJSON(src []byte) error { @@ -124,4 +124,3 @@ func (v *NullableDog) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog_all_of.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog_all_of.go index e7df31a2e4d..19e81717139 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog_all_of.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_dog_all_of.go @@ -63,7 +63,7 @@ func (v NullableDogAllOf) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableDogAllOf) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableDogAllOf) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_arrays.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_arrays.go index 5944a22e035..104d4a22b39 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_arrays.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_arrays.go @@ -97,7 +97,7 @@ func (v NullableEnumArrays) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumArrays) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableEnumArrays) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_class.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_class.go index 8271d1de643..4f97b16b8ef 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_class.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_class.go @@ -31,13 +31,11 @@ type NullableEnumClass struct { func (v NullableEnumClass) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumClass) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableEnumClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_test_.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_test_.go index 1dc3c855a55..426a4bfe988 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_test_.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_enum_test_.go @@ -283,7 +283,7 @@ func (v NullableEnumTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableEnumTest) UnmarshalJSON(src []byte) error { @@ -294,4 +294,3 @@ func (v *NullableEnumTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file.go index bff1e6aab19..72ba963d094 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file.go @@ -64,7 +64,7 @@ func (v NullableFile) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFile) UnmarshalJSON(src []byte) error { @@ -75,4 +75,3 @@ func (v *NullableFile) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go index 9a4c8d2293f..6520daf2599 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_file_schema_test_class.go @@ -97,7 +97,7 @@ func (v NullableFileSchemaTestClass) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFileSchemaTestClass) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableFileSchemaTestClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_foo.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_foo.go index 4f8c45e3318..7aed18852c6 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_foo.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_foo.go @@ -63,7 +63,7 @@ func (v NullableFoo) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFoo) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableFoo) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_format_test_.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_format_test_.go index 48639a972f3..55d40bd04b7 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_format_test_.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_format_test_.go @@ -471,7 +471,7 @@ func (v NullableFormatTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableFormatTest) UnmarshalJSON(src []byte) error { @@ -482,4 +482,3 @@ func (v *NullableFormatTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go index 6ff753d0744..ba4d6b6bc0f 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_has_only_read_only.go @@ -97,7 +97,7 @@ func (v NullableHasOnlyReadOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableHasOnlyReadOnly) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableHasOnlyReadOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_health_check_result.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_health_check_result.go index 936c1fc8880..d6b450bb910 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_health_check_result.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_health_check_result.go @@ -63,7 +63,7 @@ func (v NullableHealthCheckResult) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableHealthCheckResult) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableHealthCheckResult) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object.go index 1dd06726eb5..05152802669 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object.go @@ -99,7 +99,7 @@ func (v NullableInlineObject) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject) UnmarshalJSON(src []byte) error { @@ -110,4 +110,3 @@ func (v *NullableInlineObject) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_1.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_1.go index 9deaf79e09f..b718912b270 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_1.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_1.go @@ -100,7 +100,7 @@ func (v NullableInlineObject1) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject1) UnmarshalJSON(src []byte) error { @@ -111,4 +111,3 @@ func (v *NullableInlineObject1) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_2.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_2.go index 9db10a658bb..fe7e129e3f5 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_2.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_2.go @@ -99,7 +99,7 @@ func (v NullableInlineObject2) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject2) UnmarshalJSON(src []byte) error { @@ -110,4 +110,3 @@ func (v *NullableInlineObject2) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_3.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_3.go index 17c1a53b2fc..e840bc4d75c 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_3.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_3.go @@ -449,7 +449,7 @@ func (v NullableInlineObject3) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject3) UnmarshalJSON(src []byte) error { @@ -460,4 +460,3 @@ func (v *NullableInlineObject3) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_4.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_4.go index ec72ab8d1f1..8a17ec87e22 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_4.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_4.go @@ -63,7 +63,7 @@ func (v NullableInlineObject4) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject4) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableInlineObject4) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_5.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_5.go index c65df83e7af..8f4553ae280 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_5.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_object_5.go @@ -82,7 +82,7 @@ func (v NullableInlineObject5) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineObject5) UnmarshalJSON(src []byte) error { @@ -93,4 +93,3 @@ func (v *NullableInlineObject5) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_response_default.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_response_default.go index 5d974dfc4c6..9caab8b3791 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_response_default.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_inline_response_default.go @@ -63,7 +63,7 @@ func (v NullableInlineResponseDefault) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableInlineResponseDefault) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableInlineResponseDefault) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_list.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_list.go index 70b77ab6642..18ef3c182ad 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_list.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_list.go @@ -63,7 +63,7 @@ func (v NullableList) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableList) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableList) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_map_test_.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_map_test_.go index a0731be7850..f4e3ea57c90 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_map_test_.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_map_test_.go @@ -165,7 +165,7 @@ func (v NullableMapTest) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableMapTest) UnmarshalJSON(src []byte) error { @@ -176,4 +176,3 @@ func (v *NullableMapTest) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go index 4ccc42689a3..1a0d83380c7 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mixed_properties_and_additional_properties_class.go @@ -132,7 +132,7 @@ func (v NullableMixedPropertiesAndAdditionalPropertiesClass) MarshalJSON() ([]by return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableMixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(src []byte) error { @@ -143,4 +143,3 @@ func (v *NullableMixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(src return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_name.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_name.go index b37ee67d233..6256aa5c2b3 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_name.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_name.go @@ -147,7 +147,7 @@ func (v NullableName) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableName) UnmarshalJSON(src []byte) error { @@ -158,4 +158,3 @@ func (v *NullableName) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_nullable_class.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_nullable_class.go index 4ab8dfc1c2a..74d39932b11 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_nullable_class.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_nullable_class.go @@ -438,7 +438,7 @@ func (v NullableNullableClass) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableNullableClass) UnmarshalJSON(src []byte) error { @@ -449,4 +449,3 @@ func (v *NullableNullableClass) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_number_only.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_number_only.go index f7b79fd08aa..db549197413 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_number_only.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_number_only.go @@ -63,7 +63,7 @@ func (v NullableNumberOnly) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableNumberOnly) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableNumberOnly) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_order.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_order.go index 20c5d9c1384..b90caa6101e 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_order.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_order.go @@ -235,7 +235,7 @@ func (v NullableOrder) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOrder) UnmarshalJSON(src []byte) error { @@ -246,4 +246,3 @@ func (v *NullableOrder) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_composite.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_composite.go index 1943fda269f..cd40b710988 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_composite.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_composite.go @@ -131,7 +131,7 @@ func (v NullableOuterComposite) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterComposite) UnmarshalJSON(src []byte) error { @@ -142,4 +142,3 @@ func (v *NullableOuterComposite) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum.go index c1763b7bd2f..8e7b562c1e5 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum.go @@ -31,13 +31,11 @@ type NullableOuterEnum struct { func (v NullableOuterEnum) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterEnum) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableOuterEnum) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_default_value.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_default_value.go index e19de0cdc50..3305aa215fe 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_default_value.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_default_value.go @@ -31,13 +31,11 @@ type NullableOuterEnumDefaultValue struct { func (v NullableOuterEnumDefaultValue) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterEnumDefaultValue) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableOuterEnumDefaultValue) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer.go index e80a8e2522e..2d144b70d55 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer.go @@ -31,13 +31,11 @@ type NullableOuterEnumInteger struct { func (v NullableOuterEnumInteger) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterEnumInteger) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableOuterEnumInteger) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer_default_value.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer_default_value.go index 5d1811ef9d7..d7290302094 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer_default_value.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_outer_enum_integer_default_value.go @@ -31,13 +31,11 @@ type NullableOuterEnumIntegerDefaultValue struct { func (v NullableOuterEnumIntegerDefaultValue) MarshalJSON() ([]byte, error) { switch { - case v.ExplicitNull && v.Value != "": - return nil, ErrInvalidNullable case v.ExplicitNull: return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableOuterEnumIntegerDefaultValue) UnmarshalJSON(src []byte) error { @@ -48,6 +46,3 @@ func (v *NullableOuterEnumIntegerDefaultValue) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - - - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_pet.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_pet.go index bbd29397b4c..0986a674066 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_pet.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_pet.go @@ -198,7 +198,7 @@ func (v NullablePet) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullablePet) UnmarshalJSON(src []byte) error { @@ -209,4 +209,3 @@ func (v *NullablePet) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_read_only_first.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_read_only_first.go index 3b9b68414c0..24f821d7bdf 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_read_only_first.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_read_only_first.go @@ -97,7 +97,7 @@ func (v NullableReadOnlyFirst) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableReadOnlyFirst) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableReadOnlyFirst) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_return.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_return.go index 4d5af7cda2b..c5b2d1aaecc 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_return.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_return.go @@ -63,7 +63,7 @@ func (v NullableReturn) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableReturn) UnmarshalJSON(src []byte) error { @@ -74,4 +74,3 @@ func (v *NullableReturn) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_tag.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_tag.go index 885ba363bd2..f50a11101e4 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_tag.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_tag.go @@ -97,7 +97,7 @@ func (v NullableTag) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableTag) UnmarshalJSON(src []byte) error { @@ -108,4 +108,3 @@ func (v *NullableTag) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_user.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_user.go index 1b280a841ce..dc7234de91b 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_user.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_user.go @@ -302,7 +302,7 @@ func (v NullableUser) MarshalJSON() ([]byte, error) { return []byte("null"), nil default: return json.Marshal(v.Value) - } + } } func (v *NullableUser) UnmarshalJSON(src []byte) error { @@ -313,4 +313,3 @@ func (v *NullableUser) UnmarshalJSON(src []byte) error { return json.Unmarshal(src, &v.Value) } - diff --git a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php index 6c30b5ef3f2..3f9e16f0115 100644 --- a/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php +++ b/samples/openapi3/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php @@ -82,8 +82,8 @@ class HeaderSelector { if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { return null; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; + } elseif ($jsonAccept = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept)) { + return implode(',', $jsonAccept); } else { return implode(',', $accept); } diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 907737d8b0e..45ff3402d25 100644 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -23,7 +23,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import petstore_api +import petstore_api ``` ### Setuptools diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index 91109c7d78c..1c9522f71c5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -341,41 +341,37 @@ class Configuration(object): } ] - def get_host_from_settings(self, index, variables={}): + def get_host_from_settings(self, index, variables=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ - + variables = {} if variables is None else variables servers = self.get_host_settings() - # check array index out of bound - if index < 0 or index >= len(servers): + try: + server = servers[index] + except IndexError: raise ValueError( - "Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501 - .format(index, len(servers))) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - server = servers[index] url = server['url'] - # go through variable and assign a value - for variable_name in server['variables']: - if variable_name in variables: - if variables[variable_name] in server['variables'][ - variable_name]['enum_values']: - url = url.replace("{" + variable_name + "}", - variables[variable_name]) - else: - raise ValueError( - "The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501 - .format( - variable_name, variables[variable_name], - server['variables'][variable_name]['enum_values'])) - else: - # use default value - url = url.replace( - "{" + variable_name + "}", - server['variables'][variable_name]['default_value']) + # go through variables and replace placeholders + for variable_name, variable in server['variables'].items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) return url diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt index acf21c3e9fd..b2286383f87 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt @@ -17,10 +17,10 @@ import org.openapitools.server.models.Tag import java.io.Serializable /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/server/petstore/kotlin-springboot-reactive/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot-reactive/src/main/kotlin/org/openapitools/model/Pet.kt index 4a2e9d26cb9..e92ce409479 100644 --- a/samples/server/petstore/kotlin-springboot-reactive/src/main/kotlin/org/openapitools/model/Pet.kt +++ b/samples/server/petstore/kotlin-springboot-reactive/src/main/kotlin/org/openapitools/model/Pet.kt @@ -16,10 +16,10 @@ import io.swagger.annotations.ApiModelProperty /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt index 4a2e9d26cb9..e92ce409479 100644 --- a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt @@ -16,10 +16,10 @@ import io.swagger.annotations.ApiModelProperty /** * A pet for sale in the pet store - * @param id - * @param category * @param name * @param photoUrls + * @param id + * @param category * @param tags * @param status pet status in the store */ diff --git a/samples/server/petstore/php-slim4/composer.json b/samples/server/petstore/php-slim4/composer.json index 3a82d6db53f..4a45af2568d 100644 --- a/samples/server/petstore/php-slim4/composer.json +++ b/samples/server/petstore/php-slim4/composer.json @@ -29,10 +29,12 @@ "scripts": { "test": [ "@test-apis", - "@test-models" + "@test-models", + "@test-mock" ], "test-apis": "phpunit --testsuite Apis", "test-models": "phpunit --testsuite Models", + "test-mock": "phpunit --testsuite Mock", "phpcs": "phpcs", "phplint": "phplint ./ --exclude=vendor" } diff --git a/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMocker.php b/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMocker.php new file mode 100644 index 00000000000..fe0b10f2db7 --- /dev/null +++ b/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMocker.php @@ -0,0 +1,362 @@ +mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + return $this->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + case IMocker::DATA_TYPE_STRING: + $minLength = $options['minLength'] ?? 0; + $maxLength = $options['maxLength'] ?? null; + return $this->mockString($dataFormat, $minLength, $maxLength); + case IMocker::DATA_TYPE_BOOLEAN: + return $this->mockBoolean(); + case IMocker::DATA_TYPE_ARRAY: + $items = $options['items'] ?? null; + $minItems = $options['minItems'] ?? 0; + $maxItems = $options['maxItems'] ?? null; + $uniqueItems = $options['uniqueItems'] ?? false; + return $this->mockArray($items, $minItems, $maxItems, $uniqueItems); + default: + throw new InvalidArgumentException('"dataType" must be one of ' . implode(', ', [ + IMocker::DATA_TYPE_INTEGER, + IMocker::DATA_TYPE_NUMBER, + IMocker::DATA_TYPE_STRING, + IMocker::DATA_TYPE_BOOLEAN, + IMocker::DATA_TYPE_ARRAY, + ])); + } + } + + /** + * Shortcut to mock integer type + * Equivalent to mockData(DATA_TYPE_INTEGER); + * + * @param string|null $dataFormat (optional) int32 or int64 + * @param number|null $minimum (optional) Default is 0 + * @param number|null $maximum (optional) Default is mt_getrandmax() + * @param bool|null $exclusiveMinimum (optional) Default is false + * @param bool|null $exclusiveMaximum (optional) Default is false + * + * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided + * + * @return int + */ + public function mockInteger( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 0); + } + + /** + * Shortcut to mock number type + * Equivalent to mockData(DATA_TYPE_NUMBER); + * + * @param string|null $dataFormat (optional) float or double + * @param number|null $minimum (optional) Default is 0 + * @param number|null $maximum (optional) Default is mt_getrandmax() + * @param bool|null $exclusiveMinimum (optional) Default is false + * @param bool|null $exclusiveMaximum (optional) Default is false + * + * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided + * + * @return float + */ + public function mockNumber( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 4); + } + + /** + * Shortcut to mock string type + * Equivalent to mockData(DATA_TYPE_STRING); + * + * @param string|null $dataFormat (optional) one of byte, binary, date, date-time, password + * @param int|null $minLength (optional) Default is 0 + * @param int|null $maxLength (optional) Default is 100 chars + * @param array $enum (optional) This array should have at least one element. + * Elements in the array should be unique. + * @param string|null $pattern (optional) This string should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * Recall: regular expressions are not implicitly anchored. + * + * @throws \InvalidArgumentException when invalid arguments passed + * + * @return string + */ + public function mockString( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null, + $pattern = null + ) { + if ($enum !== null) { + if ( + is_array($enum) === false + || empty($enum) + || count($enum) > count(array_unique($enum)) + ) { + throw new InvalidArgumentException('"enum" must be an array. This array should have at least one element. Elements in the array should be unique.'); + } + + // return random variant + return $enum[mt_rand(0, count($enum) - 1)]; + } + + if ($minLength !== 0 && $minLength !== null) { + if (is_int($minLength) === false) { + throw new InvalidArgumentException('"minLength" must be an integer'); + } elseif ($minLength < 0) { + throw new InvalidArgumentException('"minLength" must be greater than, or equal to, 0'); + } + } else { + $minLength = 0; + } + + if ($maxLength !== null) { + if (is_int($maxLength) === false) { + throw new InvalidArgumentException('"maxLength" must be an integer'); + } elseif ($maxLength < 0) { + throw new InvalidArgumentException('"maxLength" must be greater than, or equal to, 0'); + } + } else { + // since we don't need huge texts by default, lets cut them down to 100 chars + $maxLength = 100; + } + + if ($maxLength < $minLength) { + throw new InvalidArgumentException('"maxLength" value cannot be less than "minLength"'); + } + + return str_pad('', mt_rand($minLength, $maxLength), 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', \STR_PAD_RIGHT); + } + + /** + * Shortcut to mock boolean type + * Equivalent to mockData(DATA_TYPE_BOOLEAN); + * + * @return bool + */ + public function mockBoolean() + { + return (bool) mt_rand(0, 1); + } + + /** + * Shortcut to mock array type + * Equivalent to mockData(DATA_TYPE_ARRAY); + * + * @param array $items Array of described items + * @param int|null $minItems (optional) An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. + * @param int|null $maxItems (optional) An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword + * @param bool|null $uniqueItems (optional) If it has boolean value true, the instance validates successfully if all of its elements are unique + * + * @throws \InvalidArgumentException when invalid arguments passed + * + * @return array + */ + public function mockArray( + $items, + $minItems = 0, + $maxItems = null, + $uniqueItems = false + ) { + $arr = []; + $minSize = 0; + $maxSize = \PHP_INT_MAX; + + if (is_array($items) === false || array_key_exists('type', $items) === false) { + throw new InvalidArgumentException('"items" must be assoc array with "type" key'); + } + + if ($minItems !== null) { + if (is_integer($minItems) === false || $minItems < 0) { + throw new InvalidArgumentException('"mitItems" must be an integer. This integer must be greater than, or equal to, 0'); + } + $minSize = $minItems; + } + + if ($maxItems !== null) { + if (is_integer($maxItems) === false || $maxItems < 0) { + throw new InvalidArgumentException('"maxItems" must be an integer. This integer must be greater than, or equal to, 0.'); + } + if ($maxItems < $minItems) { + throw new InvalidArgumentException('"maxItems" value cannot be less than "minItems"'); + } + $maxSize = $maxItems; + } + + $dataType = $items['type']; + $dataFormat = $items['format'] ?? null; + $options = $this->extractSchemaProperties($items); + + // always genarate smallest possible array to avoid huge JSON responses + $arrSize = ($maxSize < 1) ? $maxSize : max($minSize, 1); + while (count($arr) < $arrSize) { + $arr[] = $this->mock($dataType, $dataFormat, $options); + } + return $arr; + } + + /** + * @internal Extract OAS properties from array or object. + * + * @param array $arr Processed array + * + * @return array + */ + private function extractSchemaProperties($arr) + { + $props = []; + foreach ( + [ + 'minimum', + 'maximum', + 'exclusiveMinimum', + 'exclusiveMaximum', + 'minLength', + 'maxLength', + 'pattern', + 'enum', + 'items', + 'minItems', + 'maxItems', + 'uniqueItems', + 'properties', + 'minProperties', + 'maxProperties', + 'additionalProperties', + 'required', + 'example', + ] as $propName + ) { + if (array_key_exists($propName, $arr)) { + $props[$propName] = $arr[$propName]; + } + } + return $props; + } + + /** + * @internal + * + * @return float|int + */ + protected function getRandomNumber( + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $maxDecimals = 4 + ) { + $min = 0; + $max = mt_getrandmax(); + + if ($minimum !== null) { + if (is_numeric($minimum) === false) { + throw new InvalidArgumentException('"minimum" must be a number'); + } + $min = $minimum; + } + + if ($maximum !== null) { + if (is_numeric($maximum) === false) { + throw new InvalidArgumentException('"maximum" must be a number'); + } + $max = $maximum; + } + + if ($exclusiveMinimum !== false) { + if (is_bool($exclusiveMinimum) === false) { + throw new InvalidArgumentException('"exclusiveMinimum" must be a boolean'); + } elseif ($minimum === null) { + throw new InvalidArgumentException('If "exclusiveMinimum" is present, "minimum" must also be present'); + } + $min += 1; + } + + if ($exclusiveMaximum !== false) { + if (is_bool($exclusiveMaximum) === false) { + throw new InvalidArgumentException('"exclusiveMaximum" must be a boolean'); + } elseif ($maximum === null) { + throw new InvalidArgumentException('If "exclusiveMaximum" is present, "maximum" must also be present'); + } + $max -= 1; + } + + if ($max < $min) { + throw new InvalidArgumentException('"maximum" value cannot be less than "minimum"'); + } + + if ($maxDecimals > 0) { + return round($min + mt_rand() / mt_getrandmax() * ($max - $min), $maxDecimals); + } + return mt_rand($min, $max); + } +} diff --git a/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php b/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php new file mode 100644 index 00000000000..fc6e28986d7 --- /dev/null +++ b/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php @@ -0,0 +1,204 @@ + ./test/Model + + ./test/Mock + ./lib/Api ./lib/Model + ./lib/Mock diff --git a/samples/server/petstore/php-slim4/pom.xml b/samples/server/petstore/php-slim4/pom.xml new file mode 100644 index 00000000000..30f1410a70c --- /dev/null +++ b/samples/server/petstore/php-slim4/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + org.opoenapitools + Slim4PetstoreServerTests + pom + 1.0-SNAPSHOT + Slim4 Petstore Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + syntax-check + integration-test + + exec + + + ./php_syntax_checker.bash + + + + + + + diff --git a/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php b/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php new file mode 100644 index 00000000000..221e6c6bf66 --- /dev/null +++ b/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php @@ -0,0 +1,578 @@ +assertInternalType($expectedType, $mocker->mock($dataType)); + } + + public function provideMockCorrectArguments() + { + return [ + [IMocker::DATA_TYPE_INTEGER, null, null, IsType::TYPE_INT], + [IMocker::DATA_TYPE_NUMBER, null, null, IsType::TYPE_FLOAT], + [IMocker::DATA_TYPE_STRING, null, null, IsType::TYPE_STRING], + [IMocker::DATA_TYPE_BOOLEAN, null, null, IsType::TYPE_BOOL], + ]; + } + + /** + * @dataProvider provideMockIntegerCorrectArguments + * @covers ::mockInteger + */ + public function testMockIntegerWithCorrectArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + + $this->internalAssertNumber( + $integer, + $minimum, + $maximum, + $exclusiveMinimum, + $exclusiveMaximum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockIntegerCorrectArguments() + { + $types = [ + IsType::TYPE_INT, + IsType::TYPE_NUMERIC, + IsType::TYPE_SCALAR, + ]; + $notTypes = [ + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_FLOAT, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_STRING, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, -100, 100, false, false, $types, $notTypes], + [null, -100, null, false, false, $types, $notTypes], + [null, null, 100, false, false, $types, $notTypes], + [null, -99.5, null, true, false, $types, $notTypes], + [null, null, 99.5, false, true, $types, $notTypes], + [null, -99.5, 99.5, true, true, $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockIntegerInvalidArguments + * @covers ::mockInteger + * @expectedException \InvalidArgumentException + */ + public function testMockIntegerWithInvalidArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + $mocker = new OpenApiDataMocker(); + $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + + public function provideMockIntegerInvalidArguments() + { + return [ + [null, 'foo', null, false, false], + [null, null, false, false, false], + [null, null, null, true, false], + [null, null, null, false, true], + [null, 100, -100, false, false], + ]; + } + + /** + * @dataProvider provideMockNumberCorrectArguments + * @covers ::mockNumber + */ + public function testMockNumberWithCorrectArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + + $this->internalAssertNumber( + $number, + $minimum, + $maximum, + $exclusiveMinimum, + $exclusiveMaximum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockNumberCorrectArguments() + { + $types = [ + IsType::TYPE_SCALAR, + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + ]; + $notTypes = [ + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_STRING, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, -100, 100, false, false, $types, $notTypes], + [null, -100, null, false, false, $types, $notTypes], + [null, null, 100, false, false, $types, $notTypes], + [null, -99.5, null, true, false, $types, $notTypes], + [null, null, 99.5, false, true, $types, $notTypes], + [null, -99.5, 99.5, true, true, $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockNumberInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockNumber + */ + public function testMockNumberWithInvalidArguments( + $dataFormat = null, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false + ) { + $mocker = new OpenApiDataMocker(); + $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + } + + public function provideMockNumberInvalidArguments() + { + return [ + [null, 'foo', null, false, false], + [null, null, false, false, false], + [null, null, null, true, false], + [null, null, null, false, true], + [null, 100, -100, false, false], + ]; + } + + /** + * @dataProvider provideMockStringCorrectArguments + * @covers ::mockString + */ + public function testMockStringWithCorrectArguments( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + $mocker = new OpenApiDataMocker(); + $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); + + $this->internalAssertString( + $str, + $minLength, + $maxLength, + $enum, + $matchingInternalTypes, + $notMatchingInternalTypes + ); + } + + public function provideMockStringCorrectArguments() + { + $types = [ + IsType::TYPE_SCALAR, + IsType::TYPE_STRING, + ]; + $notTypes = [ + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_BOOL, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_CALLABLE, + ]; + + return [ + [null, 0, null, null, $types, $notTypes], + [null, 10, null, null, $types, $notTypes], + [null, 0, 100, null, $types, $notTypes], + [null, 10, 50, null, $types, $notTypes], + [null, 10, 10, null, $types, $notTypes], + [null, 0, 0, null, $types, $notTypes], + [null, null, null, null, $types, $notTypes], + [null, null, null, ['foobar', 'foobaz', 'hello world'], $types, $notTypes], + [null, null, null, ['foobar'], $types, $notTypes], + ]; + } + + /** + * @dataProvider provideMockStringInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockString + */ + public function testMockStringWithInvalidArguments( + $dataFormat = null, + $minLength = 0, + $maxLength = null, + $enum = null + ) { + $mocker = new OpenApiDataMocker(); + $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); + } + + public function provideMockStringInvalidArguments() + { + return [ + 'negative minLength' => [null, -10, null], + 'negative maxLength' => [null, 0, -10], + 'both minLength maxLength negative' => [null, -10, -10], + 'decimal minLength and maxLength' => [null, 0.5, 0.5], + 'string minLength' => [null, '10', null], + 'string maxLength' => [null, 0, '50'], + 'string minLength and maxLength' => [null, '10', '50'], + 'maxLength less than minLength' => [null, 50, 10], + 'enum is string' => [null, null, null, 'foobar'], + 'enum is empty array' => [null, null, null, []], + 'enum array is not unique' => [null, null, null, ['foobar', 'foobaz', 'foobar']], + ]; + } + + /** + * @covers ::mockBoolean + */ + public function testMockBoolean() + { + $mocker = new OpenApiDataMocker(); + $bool = $mocker->mockBoolean(); + + $matchingInternalTypes = [ + IsType::TYPE_SCALAR, + IsType::TYPE_BOOL, + ]; + + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $bool); + } + + $notMatchingInternalTypes = [ + IsType::TYPE_NUMERIC, + IsType::TYPE_FLOAT, + IsType::TYPE_INT, + IsType::TYPE_ARRAY, + IsType::TYPE_STRING, + IsType::TYPE_NULL, + IsType::TYPE_OBJECT, + IsType::TYPE_RESOURCE, + IsType::TYPE_CALLABLE, + ]; + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $bool); + } + } + + private function internalAssertNumber( + $number, + $minimum = null, + $maximum = null, + $exclusiveMinimum = false, + $exclusiveMaximum = false, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $number); + } + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $number); + } + + if ($minimum !== null) { + if ($exclusiveMinimum) { + $this->assertGreaterThan($minimum, $number); + } else { + $this->assertGreaterThanOrEqual($minimum, $number); + } + } + + if ($maximum !== null) { + if ($exclusiveMaximum) { + $this->assertLessThan($maximum, $number); + } else { + $this->assertLessThanOrEqual($maximum, $number); + } + } + } + + private function internalAssertString( + $str, + $minLength = null, + $maxLength = null, + $enum = null, + $matchingInternalTypes = [], + $notMatchingInternalTypes = [] + ) { + foreach ($matchingInternalTypes as $matchType) { + $this->assertInternalType($matchType, $str); + } + + foreach ($notMatchingInternalTypes as $notMatchType) { + $this->assertNotInternalType($notMatchType, $str); + } + + if ($minLength !== null) { + $this->assertGreaterThanOrEqual($minLength, mb_strlen($str, 'UTF-8')); + } + + if ($maxLength !== null) { + $this->assertLessThanOrEqual($maxLength, mb_strlen($str, 'UTF-8')); + } + + if (is_array($enum) && !empty($enum)) { + $this->assertContains($str, $enum); + } + } + + /** + * @dataProvider provideMockArrayCorrectArguments + * @covers ::mockArray + */ + public function testMockArrayFlattenWithCorrectArguments( + $items, + $minItems, + $maxItems, + $uniqueItems, + $expectedItemsType = null, + $expectedArraySize = null + ) { + $mocker = new OpenApiDataMocker(); + $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); + + $this->assertIsArray($arr); + if ($expectedArraySize !== null) { + $this->assertCount($expectedArraySize, $arr); + } + if ($expectedItemsType && $expectedArraySize > 0) { + $this->assertContainsOnly($expectedItemsType, $arr, true); + } + + $dataFormat = $items['dataFormat'] ?? null; + + // items field numeric properties + $minimum = $items['minimum'] ?? null; + $maximum = $items['maximum'] ?? null; + $exclusiveMinimum = $items['exclusiveMinimum'] ?? null; + $exclusiveMaximum = $items['exclusiveMaximum'] ?? null; + + // items field string properties + $minLength = $items['minLength'] ?? null; + $maxLength = $items['maxLength'] ?? null; + $enum = $items['enum'] ?? null; + $pattern = $items['pattern'] ?? null; + + // items field array properties + $subItems = $items['items'] ?? null; + $subMinItems = $items['minItems'] ?? null; + $subMaxItems = $items['maxItems'] ?? null; + $subUniqueItems = $items['uniqueItems'] ?? null; + + foreach ($arr as $item) { + switch ($items['type']) { + case IMocker::DATA_TYPE_INTEGER: + $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + break; + case IMocker::DATA_TYPE_NUMBER: + $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); + break; + case IMocker::DATA_TYPE_STRING: + $this->internalAssertString($item, $minLength, $maxLength); + break; + case IMocker::DATA_TYPE_BOOLEAN: + $this->assertInternalType(IsType::TYPE_BOOL, $item); + break; + case IMocker::DATA_TYPE_ARRAY: + $this->testMockArrayFlattenWithCorrectArguments($subItems, $subMinItems, $subMaxItems, $subUniqueItems); + break; + } + } + } + + public function provideMockArrayCorrectArguments() + { + $intItems = ['type' => IMocker::DATA_TYPE_INTEGER, 'minimum' => 5, 'maximum' => 10]; + $floatItems = ['type' => IMocker::DATA_TYPE_NUMBER, 'minimum' => -32.4, 'maximum' => 88.6, 'exclusiveMinimum' => true, 'exclusiveMaximum' => true]; + $strItems = ['type' => IMocker::DATA_TYPE_STRING, 'minLength' => 20, 'maxLength' => 50]; + $boolItems = ['type' => IMocker::DATA_TYPE_BOOLEAN]; + $arrayItems = ['type' => IMocker::DATA_TYPE_ARRAY, 'items' => ['type' => IMocker::DATA_TYPE_STRING, 'minItems' => 3, 'maxItems' => 10]]; + $expectedInt = IsType::TYPE_INT; + $expectedFloat = IsType::TYPE_FLOAT; + $expectedStr = IsType::TYPE_STRING; + $expectedBool = IsType::TYPE_BOOL; + $expectedArray = IsType::TYPE_ARRAY; + + return [ + 'empty array' => [ + $strItems, null, 0, false, null, 0, + ], + 'empty array, limit zero' => [ + $strItems, 0, 0, false, null, 0, + ], + 'array of one string as default size' => [ + $strItems, null, null, false, $expectedStr, 1, + ], + 'array of one string, limit one' => [ + $strItems, 1, 1, false, $expectedStr, 1, + ], + 'array of two strings' => [ + $strItems, 2, null, false, $expectedStr, 2, + ], + 'array of five strings, limit ten' => [ + $strItems, 5, 10, false, $expectedStr, 5, + ], + 'array of five strings, limit five' => [ + $strItems, 5, 5, false, $expectedStr, 5, + ], + 'array of one string, limit five' => [ + $strItems, null, 5, false, $expectedStr, 1, + ], + 'array of one integer' => [ + $intItems, null, null, false, $expectedInt, 1, + ], + 'array of one float' => [ + $floatItems, null, null, false, $expectedFloat, 1, + ], + 'array of one boolean' => [ + $boolItems, null, null, false, $expectedBool, 1, + ], + 'array of one array of strings' => [ + $arrayItems, null, null, false, $expectedArray, 1, + ], + ]; + } + + /** + * @dataProvider provideMockArrayInvalidArguments + * @expectedException \InvalidArgumentException + * @covers ::mockArray + */ + public function testMockArrayWithInvalidArguments( + $items, + $minItems, + $maxItems, + $uniqueItems + ) { + $mocker = new OpenApiDataMocker(); + $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); + } + + public function provideMockArrayInvalidArguments() + { + $intItems = ['type' => IMocker::DATA_TYPE_INTEGER]; + + return [ + 'items is nor array' => [ + 'foobar', null, null, false, + ], + 'items doesnt have "type" key' => [ + ['foobar' => 'foobaz'], null, null, false, + ], + 'minItems is not integer' => [ + $intItems, 3.12, null, false, + ], + 'minItems is negative' => [ + $intItems, -10, null, false, + ], + 'minItems is not number' => [ + $intItems, '1', null, false, + ], + 'maxItems is not integer' => [ + $intItems, null, 3.12, false, + ], + 'maxItems is negative' => [ + $intItems, null, -10, false, + ], + 'maxItems is not number' => [ + $intItems, null, 'foobaz', false, + ], + 'maxItems less than minItems' => [ + $intItems, 5, 2, false, + ], + ]; + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java index be133550f1e..78f98e13a89 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java @@ -78,7 +78,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default CompletableFuture> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default CompletableFuture> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -97,7 +97,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default CompletableFuture> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default CompletableFuture> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { return CompletableFuture.supplyAsync(()-> { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { @@ -127,7 +127,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default CompletableFuture> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default CompletableFuture> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } @@ -146,7 +146,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default CompletableFuture> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default CompletableFuture> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)); } diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java index 7f5a05ea657..383f72f483d 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java @@ -77,7 +77,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -96,7 +96,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { @@ -124,7 +124,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -143,7 +143,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java index 15674356e88..a4f9566f457 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java @@ -66,7 +66,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); /** @@ -82,7 +82,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); /** @@ -98,7 +98,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); /** @@ -114,7 +114,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); /** diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java index aac6a3e3b1d..7b194d00458 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java @@ -62,7 +62,7 @@ public class FakeApiController implements FakeApi { * @return Output boolean (status code 200) * @see FakeApi#fakeOuterBooleanSerialize */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -75,7 +75,7 @@ public class FakeApiController implements FakeApi { * @return Output composite (status code 200) * @see FakeApi#fakeOuterCompositeSerialize */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; @@ -95,7 +95,7 @@ public class FakeApiController implements FakeApi { * @return Output number (status code 200) * @see FakeApi#fakeOuterNumberSerialize */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -108,7 +108,7 @@ public class FakeApiController implements FakeApi { * @return Output string (status code 200) * @see FakeApi#fakeOuterStringSerialize */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java index 15674356e88..a4f9566f457 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java @@ -66,7 +66,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); /** @@ -82,7 +82,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); /** @@ -98,7 +98,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); /** @@ -114,7 +114,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); /** diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java index 828761ab32e..05c54707b03 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java @@ -62,7 +62,7 @@ public class FakeApiController implements FakeApi { * @return Output boolean (status code 200) * @see FakeApi#fakeOuterBooleanSerialize */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -75,7 +75,7 @@ public class FakeApiController implements FakeApi { * @return Output composite (status code 200) * @see FakeApi#fakeOuterCompositeSerialize */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; @@ -95,7 +95,7 @@ public class FakeApiController implements FakeApi { * @return Output number (status code 200) * @see FakeApi#fakeOuterNumberSerialize */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -108,7 +108,7 @@ public class FakeApiController implements FakeApi { * @return Output string (status code 200) * @see FakeApi#fakeOuterStringSerialize */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java index ff78b2af3a4..2b8dca40157 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -72,7 +72,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return getDelegate().fakeOuterBooleanSerialize(body); } @@ -90,7 +90,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { return getDelegate().fakeOuterCompositeSerialize(body); } @@ -108,7 +108,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return getDelegate().fakeOuterNumberSerialize(body); } @@ -126,7 +126,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return getDelegate().fakeOuterStringSerialize(body); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index 15674356e88..a4f9566f457 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -66,7 +66,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body); + ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); /** @@ -82,7 +82,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body); + ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); /** @@ -98,7 +98,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body); + ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); /** @@ -114,7 +114,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body); + ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); /** diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java index 705a9150f76..af0a6322c08 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java @@ -59,7 +59,7 @@ public class FakeApiController implements FakeApi { * @return Output boolean (status code 200) * @see FakeApi#fakeOuterBooleanSerialize */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return delegate.fakeOuterBooleanSerialize(body); } @@ -71,7 +71,7 @@ public class FakeApiController implements FakeApi { * @return Output composite (status code 200) * @see FakeApi#fakeOuterCompositeSerialize */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { return delegate.fakeOuterCompositeSerialize(body); } @@ -83,7 +83,7 @@ public class FakeApiController implements FakeApi { * @return Output number (status code 200) * @see FakeApi#fakeOuterNumberSerialize */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return delegate.fakeOuterNumberSerialize(body); } @@ -95,7 +95,7 @@ public class FakeApiController implements FakeApi { * @return Output string (status code 200) * @see FakeApi#fakeOuterStringSerialize */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return delegate.fakeOuterStringSerialize(body); } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index 63f7591b04d..13928b0d16c 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -81,7 +81,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -102,7 +102,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { @@ -132,7 +132,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -153,7 +153,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java index def93bf62e1..d033a89c454 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -75,7 +75,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default Mono> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Mono body, ServerWebExchange exchange) { + default Mono> fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Mono body, ServerWebExchange exchange) { return getDelegate().fakeOuterBooleanSerialize(body, exchange); } @@ -93,7 +93,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default Mono> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody Mono body, ServerWebExchange exchange) { + default Mono> fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) Mono body, ServerWebExchange exchange) { return getDelegate().fakeOuterCompositeSerialize(body, exchange); } @@ -111,7 +111,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default Mono> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody Mono body, ServerWebExchange exchange) { + default Mono> fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) Mono body, ServerWebExchange exchange) { return getDelegate().fakeOuterNumberSerialize(body, exchange); } @@ -129,7 +129,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default Mono> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody Mono body, ServerWebExchange exchange) { + default Mono> fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) Mono body, ServerWebExchange exchange) { return getDelegate().fakeOuterStringSerialize(body, exchange); } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java index 5ed79436c9a..74a1c893690 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java @@ -77,7 +77,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -96,7 +96,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { @@ -124,7 +124,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -143,7 +143,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java index 0f0709957d5..83e03d42986 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java @@ -82,7 +82,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -102,7 +102,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { @@ -131,7 +131,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -151,7 +151,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java index 16bd728991e..a6346f9fe6d 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java @@ -77,7 +77,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/boolean", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody Boolean body) { + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -96,7 +96,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/composite", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody OuterComposite body) { + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { @@ -124,7 +124,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/number", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody BigDecimal body) { + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -143,7 +143,7 @@ public interface FakeApi { @RequestMapping(value = "/fake/outer/string", produces = { "*/*" }, method = RequestMethod.POST) - default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody String body) { + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/website/dynamic/users.yml b/website/dynamic/users.yml index 5e55dc0da8c..5ab0462aabc 100644 --- a/website/dynamic/users.yml +++ b/website/dynamic/users.yml @@ -223,6 +223,11 @@ image: "img/companies/optim.png" infoLink: "https://www.optim.co.jp/" pinned: false +- + caption: Oracle + image: "img/companies/oracle.png" + infoLink: "https://www.oracle.com" + pinned: false - caption: Paxos image: "img/companies/paxos.png" diff --git a/website/static/img/companies/oracle.png b/website/static/img/companies/oracle.png new file mode 100644 index 00000000000..b0dad3f5bbf Binary files /dev/null and b/website/static/img/companies/oracle.png differ